Using Large Language Models to Interpret NMR Spectra: A Practical AI-Assisted Analysis Guide

    Large language models can now read NMR spectra directly from images and produce structured, text-based reasoning. This guide walks through a practical workflow for AI-assisted 1H NMR interpretation: what the models can and cannot do, the inputs you need before calling a model, a step-by-step inference process with checkpoints, a reference pipeline implementation with error handling, and how to validate model output with RDKit. It is written for chemists and developers who want to integrate spectrum analysis into their lab tooling while keeping human review in the loop.

    Why NMR Spectrum Analysis Is Worth Automating with LLMs

    In chemistry research, interpreting nuclear magnetic resonance (NMR) spectra is a common, repetitive task. Researchers must map the chemical shifts, integration values, and peak splitting patterns produced by the instrument onto specific atoms in a molecular structure. Even simple small molecules can take considerable time, and structure elucidation of natural products takes even longer. The exact time depends on sample complexity and the operator’s experience, so this article does not quote fixed numbers.

    Over the past few years, many AI tools ended up gathering dust in labs, mainly for three reasons. First, traditional small models produce significant errors when handling isomers and complex coupling systems, making their results hard to use directly. Second, some tools have workflows more cumbersome than manual interpretation. Third, models often only work for molecules with specific scaffolds and fail on other sample types.

    The new generation of multimodal large language models can read spectrum images directly and provide a written reasoning process. This opens up new possibilities for the lab. However, model output is only a set of candidate conclusions—the final structure still requires human confirmation. The rest of this article describes a practical workflow, with a checkpoint at every step.

    1. Know What the Model Can and Cannot Do

    A large language model is well suited to: reading peak tables, organizing integration and splitting information, proposing candidate fragments based on common shift ranges, and assembling candidate structures into a report.

    A large language model is not suited to deciding the structure on its own, for three reasons. First, peak positions and integrations extracted from images carry errors, especially with peak overlap, baseline drift, and low signal-to-noise ratios. Second, a single 1H NMR spectrum is usually not enough to uniquely determine a molecular formula. Third, the model may fabricate plausible-sounding explanations. Therefore, the workflow must retain three safeguards: the raw data, the molecular formula, and human review.

    2. Prerequisites for the Workflow

    Before calling the model, prepare the following inputs:

    1. Molecular formula. Typically obtained from high-resolution mass spectrometry (HRMS) or elemental analysis. Without a molecular formula, you can only get candidate results, not a confirmed structure.
    2. Raw spectrum. Prefer structured files exported by the instrument, such as JCAMP-DX. Images should only be used as supplementary input, and a high-resolution version should be kept.
    3. Experimental conditions. Include the solvent, magnetic field strength, and reference standard (e.g., TMS). Residual solvent peaks must be identified by solvent type—for example, the residual proton peak of deuterated chloroform typically appears near 7.26 ppm.
    4. Reference data. This can be the lab’s internal historical spectrum library or a properly licensed public database. Confirm copyright and terms of use before use.

    3. Inference Steps and Checkpoints

    The model should reason in fixed steps, each with clear inputs and outputs.

    Step 1: Calculate the degree of unsaturation. For C8H10O: unsaturation = C − H/2 − X/2 + N/2 + 1 = 8 − 5 + 1 = 4, suggesting the molecule may contain a benzene ring. Checkpoint: the result must be consistent with the molecular formula from mass spectrometry.

    Step 2: Identify solvent and impurity peaks. Output the solvent peak positions and remove them from the candidate peak list. Checkpoint: solvent peak positions must be verified against a solvent reference table.

    Step 3: Assign functional group regions. Aromatic protons typically appear around 6.5–8.5 ppm, aldehyde protons around 9–10 ppm, and carboxylic acid protons up to 10–12 ppm. Output the candidate functional group for each region. Checkpoint: the number of candidate functional groups must be consistent with the degree of unsaturation.

    Step 4: Analyze splitting in the aliphatic region. Use the n+1 rule to infer the number of neighboring protons. For example, a triplet indicates two adjacent protons, and a quartet indicates three. Integration ratios must be converted to whole-number proton counts. Checkpoint: the sum of all integrations should equal the number of hydrogens in the molecular formula.

    Step 5: Assemble the structure and output SMILES. The model combines the fragments into a candidate molecule and produces a SMILES string. Checkpointing is delegated to RDKit, covered in the next section.

    4. Putting It into Practice: Building the Analysis Pipeline

    A single model call is not enough for stable production use. A lab can break the workflow into four stages: upload, parse, validate, and archive.

    Architecturally, raw spectra can be stored in object storage, the parsing service can be deployed in a container environment with autoscaling configured according to concurrency, and model calls can go through a dedicated LLM inference platform. If you are using Baidu AI Cloud—for example, BOS for object storage or CCE for containers—the specific API endpoints, authentication methods, request formats, and region settings should follow the current official documentation, as interfaces may change between versions.

    The following code shows only the skeleton of the pipeline, including secret handling, timeouts, retries, and response validation. Replace the endpoint details with those from the official documentation before running.

    1. import base64
    2. import os
    3. import time
    4. import requests
    5. # API endpoint and request format follow the provider's official documentation; verify before production.
    6. API_URL = os.environ["LLM_API_URL"]
    7. # Load credentials from environment variables or a secrets manager; never hard-code them in code or logs.
    8. ACCESS_TOKEN = os.environ["LLM_ACCESS_TOKEN"]
    9. TIMEOUT_SECONDS = 60
    10. MAX_RETRIES = 3
    11. PROMPT_TEMPLATE = """You are an analytical chemistry expert. Interpret the following 1H NMR spectrum based on the information below.
    12. Molecular formula: {formula}
    13. Solvent: {solvent}
    14. Output in order: solvent peak positions; chemical shift, integration, and splitting of each peak; SMILES of candidate structures;
    15. a separate list of uncertain points. Do not fabricate peaks that are not present in the spectrum."""
    16. def load_image_base64(path: str) -> str:
    17. with open(path, "rb") as f:
    18. return base64.b64encode(f.read()).decode("utf-8")
    19. def call_model(image_b64: str, formula: str, solvent: str) -> str:
    20. payload = {
    21. "messages": [{
    22. "role": "user",
    23. "content": [
    24. {"type": "text",
    25. "text": PROMPT_TEMPLATE.format(formula=formula, solvent=solvent)},
    26. {"type": "image_url",
    27. "image_url": {"url": f"data:image/png;base64,{image_b64}"}},
    28. ],
    29. }]
    30. }
    31. headers = {"Content-Type": "application/json"}
    32. params = {"access_token": ACCESS_TOKEN}
    33. for attempt in range(1, MAX_RETRIES + 1):
    34. try:
    35. resp = requests.post(API_URL, params=params, json=payload,
    36. headers=headers, timeout=TIMEOUT_SECONDS)
    37. resp.raise_for_status()
    38. body = resp.json()
    39. text = body.get("result")
    40. if not text:
    41. raise ValueError("Response is missing the result field")
    42. return text
    43. except (requests.RequestException, ValueError):
    44. if attempt == MAX_RETRIES:
    45. raise
    46. time.sleep(2 ** attempt) # exponential backoff
    47. raise RuntimeError("unreachable")

    Note: tokens passed as URL parameters may be recorded in gateway logs. If the official API supports header-based authentication, prefer that instead. Logs should only record request IDs and status codes—never full request bodies or tokens.

    5. Validating Model Output with RDKit

    SMILES strings produced by the model must be checked with cheminformatics tools. The following function performs three checks: whether the structure can be parsed, whether the valences are valid, and whether the molecular formula matches the input.

    1. from rdkit import Chem
    2. from rdkit.Chem import rdMolDescriptors
    3. def validate_candidate(smiles: str, expected_formula: str) -> dict:
    4. mol = Chem.MolFromSmiles(smiles)
    5. if mol is None:
    6. return {"ok": False, "reason": "SMILES cannot be parsed or valences are invalid"}
    7. formula = rdMolDescriptors.CalcMolFormula(mol)
    8. if formula != expected_formula:
    9. return {"ok": False, "reason": f"Formula mismatch: {formula}"}
    10. return {"ok": True, "reason": "Passed basic validation"}

    Passing validation only means the structure is chemically plausible—it does not prove it is the actual structure of the sample. The correspondence between the spectrum and the candidate structure still requires human confirmation.

    The failure-handling rules are as follows. If SMILES parsing fails, the system re-prompts the model to output only the SMILES string, and so on.