Multimodal Analysis of Spectra with Large Language Models: A Practical Pipeline for the Lab
This article explores how general-purpose large language models (LLMs) can help solve one of the laboratory's hidden bottlenecks: the manual interpretation of spectral data. It explains why spectral assignment is difficult to automate, how to structure a workflow that combines model reasoning with algorithmic validation and expert review, and which risks—such as hallucination, image quality, prompt injection, and data security—must be controlled before deployment. You will find practical guidance on data normalization, peak-level constraint generation, prompt design, tool-based validation, layered result review, evaluation metrics, and the engineering and knowledge loop needed to bring this approach into everyday R&D. The same architecture can be adapted to other expert-intensive visual and textual judgment tasks. The article also includes representative Python and JSON examples to illustrate each stage of the pipeline.
I. Background: Why Spectral Interpretation Is the Lab’s Hidden Bottleneck
Elemental analysis, mass spectrometry, infrared spectroscopy, and nuclear magnetic resonance (NMR) are standard methods for confirming the structure of organic compounds. Labs often refer to them as the “four major spectra.” Among these, assigning a proton NMR (¹H-NMR) spectrum is the most patience-testing task: a chemist must map every peak on the spectrum to a specific hydrogen in the molecule, verify that the integral ratios match the molecular formula, and infer the number of neighboring protons from the splitting pattern. For a moderately complex intermediate, a complete assignment can take anywhere from half an hour to several hours. For a novel natural product, it may require repeated comparison of 2D spectra and consume days or even weeks.
What makes this work special is that it is fundamentally a process of judgment. The model must first propose a structural hypothesis and then check it item by item against the spectral evidence. This is exactly the kind of task where the language and reasoning abilities of general-purpose LLMs can help. The challenge is that laboratory data formats are highly fragmented:
- Spectra are embedded as graphics in reports exported from instrument software, or exist only in images.
- Peak tables and integration data sit in a separate spreadsheet file.
- Structures are drawn on whiteboards or in electronic drawing tools and exist as images.
- Molecular formulas, synthetic routes, and experimental notes are plain text.
Human experts can cross-check these sources within minutes because the brain can switch freely between graphics, tables, and text. In the past, mainstream automated interpretation tools relied mainly on rule engines and narrow-domain models. They could handle only one type of spectrum or one type of structure and struggled to bridge these “format gaps.” General-purpose LLMs, by contrast, naturally possess cross-modal understanding and reasoning capabilities. This is precisely the entry point for spectral interpretation automation.
II. Problem Definition: Why General-Purpose Toolchains Keep Failing in Chemistry
Chemistry demands near-exact precision. Glucose and fructose have the same molecular formula and differ only in subtle details such as the position of the carbonyl group, yet their metabolic pathways and physiological effects are clearly different. A single epimerized amino acid in a peptide can drop activity from “highly effective” to “inactive.” As a result, automation in this field cannot be judged only by whether the workflow runs end to end. Every step must withstand review.
Automation must therefore clear three gates:
- Accuracy: Interpretation errors not only waste review time but can also mislead downstream synthesis decisions.
- Usability: The tool must fit into existing workflows without imposing additional learning costs.
- Generalization: It must handle complex targets such as natural products, metal complexes, and polymers—not just the common scaffolds found in textbooks.
General-purpose LLMs have both opportunities and weaknesses at each of these three gates:
- Reasoning advantage: They can integrate heterogeneous information such as spectra, molecular formulas, and synthetic history. Their approach is close to the human expert’s process of “propose a hypothesis, then check item by item.”
- Hallucination risk: General-purpose models do not actually “run” an instrument. They may miscalculate integrals, miscount splitting patterns, or mistake a residual solvent peak for the target molecule’s signal—and present all of it in a very confident tone.
- Environmental adaptation: They must work with existing infrastructure such as integration algorithms, molecular formula validation tools, and laboratory information management systems, rather than becoming an isolated island.
Engineering practice has therefore reached a consensus: do not treat the LLM as a standalone “automatic spectrum solver.” Instead, place it inside a closed loop of “tool validation + expert review.” Its technical positioning can be summarized as follows: algorithms handle calculation and validation; the model organizes evidence and generates conclusions; experts provide the final confirmation.
III. Solution Architecture: A Practical Spectral Interpretation Pipeline
1. Data Ingestion and Unified Normalization
Spectra files, peak tables, molecular structures, and synthesis records must first be parsed into a unified structured representation. The illustrative code below uses a peak table in CSV format as an example:
# Read peak positions, intensities, and integrals from a peak table exported by instrument software, and normalize them into a unified formatdef parse_peaks_csv(path):peaks = []with open(path, encoding="utf-8") as f:for line in csv.DictReader(f):peaks.append({"shift_ppm": float(line["shift_ppm"]), # chemical shift (ppm)"intensity": float(line["intensity"]), # peak height"integral": float(line["integral"] or 0), # integral area; may be missing})return sorted(peaks, key=lambda p: p["shift_ppm"])# Product description: used by the model to generate candidate structures and cite evidence item by itemrecord = {"spectrum": {"type": "1H-NMR", "peaks": parse_peaks_csv("h1.csv")},"formula": "C6H12O6","target": "candidate structures as SMILES strings","synthesis_notes": "……(omitted)",}
For spectra in graphical report form, a model with image-understanding capabilities first extracts descriptions of peak positions and integrals, which are then fed in as input to be validated. Whether the data comes from a table or an image, it is written into the structure shown above before any downstream processing.
2. Peak-Level Feature Engineering: Turning Integrals into Constraints
Integral areas correspond directly to the number of equivalent protons. After normalization, the integrals can be converted into integer ratios and checked against the total number of hydrogens in the molecular formula, forming a set of hard constraints:
from fractions import Fractiondef integral_ratios(integrals):total = sum(integrals)ratios = [round(Fraction(i / total).limit_denominator(12), 2) for i in integrals]scale = max(ratios) # scale relative to the largest integralreturn [float(r / scale) for r in ratios]print(integral_ratios([8.1, 12.0, 3.2, 4.7])) # output: [0.67, 1.0, 0.27, 0.39]
The example above can be read as 2 : 3 : 1 : 1.2, corresponding to 12 hydrogens in the molecular formula. Chemical shifts can also be quickly classified by region: a strong singlet below 1.5 ppm often suggests a methyl group attached to oxygen or nitrogen; solvent residual peaks are common around 3.3 ppm; 4.0–5.0 ppm is mostly oxymethine; 5.0–6.5 ppm is often vinylic hydrogen; 6.5–8.0 ppm is concentrated in aromatic hydrogens; and 9–10 ppm is generally assigned to aldehyde hydrogens. This information is supplied to the model as prior conditions.
3. Prompt Constraints and Tool Validation: Making the Model “Hypothesize First, Then Verify”
The model is responsible for generating candidate structures from the product description and for outputting the structural fragment corresponding to each signal. Calculations are delegated to executable, verifiable specialized programs. The key to the prompt is requiring it to “propose a hypothesis first, then check item by item”:
# Role: assistant for spectral interpretation of organic compounds# Inputs: peak list (chemical shift, integral), molecular formula, product description, solvent information# Tasks:# 1) Propose 3 candidate structures based on the product description;# 2) Check each candidate against the integral ratios and chemical shift regions, item by item;# 3) Output a ranked conclusion.# Constraints:# - All structures must be given as SMILES strings;# - Every conclusion must cite at least one peak's shift and integral; otherwise mark it as "insufficient evidence";# - If the sum of integrals fails an exact-divisibility check, flag the anomaly directly; do not force an assignment;# - An isolated singlet near 3.3 ppm should first be suspected as a solvent residual.# Output: strictly follow the JSON structure below.
{"candidates": [{"rank": 1, "smiles": "……", "evidence": ["d=3.7 (s, 3H)", "d=5.1 (d, 1H)"]}],"unassigned_signals": ["d=9.8 (s, 1H)"],"checks": {"formula": "pass", "integral": "pass", "unsaturation": "pass"},"confidence": "medium","notes": "……"}
# Validate candidate structures against the molecular formula: call a molecular structure processing library or use commercial cheminformatics softwarefrom rdkit import Chemfrom rdkit.Chem import rdMolDescriptorsdef validate_candidates(candidates_json, expected_formula):results = []for c in sorted(candidates_json["candidates"], key=lambda x: x["rank"]):mol = Chem.MolFromSmiles(c["smiles"])if mol is None: # unparseable SMILES is directly judged invalidresults.append({"rank": c["rank"], "formula": "invalid"})continueformula = rdMolDescriptors.CalcMolFormula(mol)results.append({"rank": c["rank"],"formula": formula,"match": formula == expected_formula, # compare against the theoretical molecular formula"evidence": c["evidence"], # every candidate comes with evidence})return results
The results returned by the tools are fed back to the model for a final judgment. The core principle is this: all judgments at the numerical and structural levels are handed over to programs, while the model only performs induction and explanation. This compresses hallucinations that are “plausible but unverifiable” into a controllable range.
4. Result Review: Rule Validation + Expert Assessment
Machine output must pass rule validation and expert spot checks before it can enter the formal report. Review can be conducted in layers:
- Soft constraints: Is the chemical shift within a reasonable range? Can the sum of integrals for signals in the same group align with the number of hydrogens in the molecular formula? Are there any “orphan peaks” that cannot be assigned?
- Hard constraints: Does the degree of unsaturation match? Is the molecular formula of the candidate structure consistent with the quasi-molecular ion given by high-resolution mass spectrometry?
Metric design must also distinguish between “scores” and “risk”:
- Assignment accuracy: the proportion of correct assignments at the peak level or structure level.
- Unsupported assertion rate: the proportion of conclusions that lack direct spectral evidence.
- Dangerous error rate: the proportion of conclusions that appear credible but are actually completely wrong.
In safety-sensitive scenarios such as chemistry, the latter two metrics are often more important than the first. Evaluation should cover a spectrum set ranging from simple small molecules to complex natural products, be tabulated in tiers, and be tracked continuously week over week. Only then can you see the true sources and bottlenecks of capability improvement.
5. Engineering Implementation and the Knowledge Loop
To enter daily R&D workflows, three kinds of support are needed:
- Workflow integration: Write interpretation results back as structured data into the laboratory information management system or electronic lab notebook, and retain the original spectrum files as traceable evidence.
- Knowledge accumulation: Organize expert-corrected cases into evaluation sets and retrieval corpora. With retrieval-augmented generation (RAG), the model can first retrieve historical interpretation records for similar compounds and similar spectra, then output conclusions, significantly reducing baseless inference.
- System support: Deploy the interpretation service as containers on a container platform; archive raw files to object storage; schedule interpretation tasks asynchronously via a message queue; and combine these with logging services and monitoring alerts to track success rate, latency, and unsupported assertion rate. For example, Baidu AI Cloud provides such general-purpose cloud product capabilities.
IV. Key Risks and Mitigations
- Hallucination: Enforce “evidence citation” for results, and uniformly mark conclusions without evidence as “pending manual confirmation.”
- Image quality: When peaks overlap severely or the baseline drifts, prompt the user directly to re-parse using integration data.
- Prompt injection: Text in instrument reports or experimental records may contain formatting anomalies. The model should treat such text only as data, not as new instructions.
- Data security: Compound structures are core R&D assets. Enforce access control, and encrypt sensitive data during transmission and storage.
V. Practical Takeaways
The value of general-purpose LLMs entering specialized domains lies not in replacing experts, but in freeing experts from mechanical information cross-checking so they can focus on structural judgment and synthesis decisions. The reusable experience can be summarized in four points:
- Hand the computable parts—integrals, molecular formulas, degrees of unsaturation—to algorithms.
- Hand cross-format induction and explanation to the model.
- Leave the final confirmation to experts.
- Use continuous evaluation to hold the line.
As long as you follow the principles of “computable, traceable, and reviewable,” the same architectural approach can be transferred to other expert-intensive visual and textual judgment scenarios—for example, geological map interpretation, materials micrograph analysis, and structured extraction from medical imaging reports. Combining general-purpose models with domain knowledge bases and specialized tools is becoming an increasingly reliable link in professional R&D workflows.
