RAG for Medical Literature Review: A Developer Guide
Build retrieval over PubMed, PMC and Europe PMC with official APIs, licence checks, PMID citations and biomedical embeddings, plus the expert review it needs.
This is a guide to research tooling: how to build retrieval-augmented generation (RAG) over biomedical papers so a model answers from documents you fetched and can cite. It is not medical advice. Nothing a pipeline like this produces should guide care, and every summary needs checking by someone with subject expertise before it goes into a review, a grant or a paper. Facts below come from the official documentation of NCBI, PMC, Europe PMC, the model publishers and the PRISMA group, linked in each section.
Where the documents come from
Three public services cover most needs. Pick by what you need to store and redistribute, not only by what you can search.
| Source | What you get | Access route |
|---|---|---|
| PubMed via E-utilities | Citations and abstracts, keyed by PMID | esearch for IDs, efetch for records (NCBI E-utilities docs) |
| PMC Open Access Subset | Full text under Creative Commons or similar licences | Cloud Service, OAI-PMH, E-utilities, BioC API |
| Europe PMC REST API | Search across PubMed and other sources, full-text links, text-mined annotations | /search returning XML, JSON or Dublin Core |
E-utilities. All nine utilities share the base URL https://eutils.ncbi.nlm.nih.gov/entrez/eutils/. ESearch returns only identifiers; you pass those to EFetch to get the records themselves. NLM’s guide caps a single ESearch at 100,000 IDs and EFetch at 10,000 records per call, with retstart and retmax for paging. Two more utilities matter for citation work: ESummary returns a short document summary per PMID, and ECitMatch looks up PubMed records from citation strings.
Europe PMC. The REST service sorts by relevance by default. A result type of core adds the abstract, full-text links and MeSH terms to each hit, and the Annotations API exposes terms mined from text, such as genes, diseases and chemicals. Using the public API means accepting the service’s privacy notice.
Rate limits and identification
NCBI publishes its rules on its policies page. In short:
- Send requests to
eutils.ncbi.nlm.nih.gov, not the regular NCBI website. - No more than three requests per second. An API key, created under Account settings in your NCBI account, lifts that to ten.
- Pass
tool(your application’s name, no spaces) andemail, so NCBI can reach you if your script misbehaves. - Run any job of more than 100 requests at weekends, or on weekdays between 9 pm and 5 am Eastern.
Licensing of full text
Free to read does not mean free to reuse. The PMC copyright notice says users are solely responsible for complying with the rights holder’s terms, and that where an article carries no copyright statement you should assume normal protection. Some journals label a paper “open access” when it is only free to read at publication.
For a RAG index, the practical rules are:
- Restrict full-text ingestion to the PMC Open Access Subset. In PubMed the filter
pubmed pmc open access[filter]finds these records. - Store each article’s licence with its chunks. PMC says terms vary from article to article, so check the licence statement before reusing text.
- Use only the automated routes PMC lists: Cloud Service, OAI-PMH, E-utilities and the BioC API. Bulk downloading from the main PMC website is banned.
- Watch for figures. PMC warns that open access and public domain papers can still contain images owned by someone else.
PMC also documents a BioC API that serves Open Access Subset full text as XML or JSON, and an ID Converter API for mapping between PMIDs, PMCIDs and DOIs. That mapping is how you keep one stable citation key whether a chunk came from an abstract or a full article.
A working example: fetch abstracts, keep the PMID
This script uses only the Python standard library. It searches PubMed, fetches the matching abstracts as XML, and keeps the PMID on every document. It sleeps between calls to stay under the documented rate and sends tool, email and an optional API key. We ran it on 8 November 2026 and it returned five records, each with a PMID, title and abstract.
import json, os, re, time, urllib.parse, urllib.request
import xml.etree.ElementTree as ET
BASE = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
IDENT = {"tool": "lit-review-rag-demo", "email": os.environ["NCBI_EMAIL"]}
if os.environ.get("NCBI_API_KEY"):
IDENT["api_key"] = os.environ["NCBI_API_KEY"]
PAUSE = 0.11 if "api_key" in IDENT else 0.34 # 10 vs 3 requests per second
def call(util, **params):
url = BASE + util + "?" + urllib.parse.urlencode({**params, **IDENT})
with urllib.request.urlopen(url, timeout=30) as r:
body = r.read()
time.sleep(PAUSE)
return body
def search(term, n=5):
data = json.loads(call("esearch.fcgi", db="pubmed", term=term, retmax=n, retmode="json"))
return data["esearchresult"]["idlist"]
def fetch(pmids):
root = ET.fromstring(call("efetch.fcgi", db="pubmed", id=",".join(pmids), retmode="xml"))
return [{
"pmid": a.findtext(".//MedlineCitation/PMID"),
"title": "".join(a.find(".//ArticleTitle").itertext()),
"abstract": " ".join("".join(t.itertext()) for t in a.iter("AbstractText")),
} for a in root.iter("PubmedArticle")]
def unknown_citations(answer, docs):
"""PMIDs the model cited that were not in the retrieved set."""
cited = set(re.findall(r"PMID:?\s*(\d+)", answer))
return cited - {d["pmid"] for d in docs}
docs = fetch(search("retrieval-augmented generation[tiab] AND systematic review[tiab]"))
From here, chunk each abstract, embed the chunks with the PMID attached as metadata, and tell the model to cite by PMID only. Our metadata filtering guide covers storing fields like PMID, licence and publication date next to vectors, and the context window guide covers chunk sizes and reranking. Frameworks such as LlamaIndex can handle the indexing if you prefer not to write it yourself.
Embedding models from their model cards
Two domain models published with official model cards are worth testing first. Microsoft’s BiomedBERT card argues that in biomedicine, pretraining on domain text from scratch beats adapting a general-domain model.
MedCPT (NCBI). The MedCPT query encoder card describes a pair of encoders: a query encoder for short texts such as questions, and an article encoder for a title plus abstract, both producing vectors in the same space. NCBI trained them on 255M query-article pairs drawn from PubMed search logs. The MedCPT repository adds a cross-encoder for reranking a shortlist, and NCBI publishes precomputed article-encoder embeddings for all of PubMed on its FTP server, keyed by PMID. The card notes the released weights differ slightly from the version in the paper, so run your own checks.
BiomedBERT (Microsoft). BiomedBERT, previously named PubMedBERT, was pretrained from scratch on PubMed abstracts and PMC full text. It is a masked-language model, not a retrieval model; MedCPT’s encoders were initialised from it. Use it as a base for fine-tuning rather than as a drop-in embedder.
NCBI’s MedCPT card also states its output is “not intended for direct diagnostic use or medical decision-making” without review by a clinical professional.
The hallucinated citation problem
A language model can produce references that look plausible but do not exist, or attach a real PMID to a claim the paper never made. Our guide to AI research agents for academics walks through how that happens with current research assistants. In a RAG pipeline, three checks catch most of it:
- Closed citation set. Reject any answer citing a PMID that was not among the retrieved documents. The
unknown_citationsfunction above does exactly this. - Existence check. For references a user pastes in, resolve them with ESummary by PMID, or ECitMatch from a citation string, before trusting them.
- Support check. A real PMID can still be the wrong source. Show the retrieved passage next to each sentence that cites it, so a reviewer can confirm the passage actually says what the sentence claims.
Evaluation and expert review
Build a small test set before you trust the pipeline. Take questions for which a domain expert has already listed the relevant PMIDs, then measure whether retrieval finds them and whether each generated sentence is backed by the passage it cites. Re-run the set whenever you change the embedding model, chunking or prompt.
If the tool feeds a systematic review, the reporting standard is PRISMA 2020. The PRISMA group describes it as a reporting guideline, mainly for reviews that evaluate interventions, made up of a statement paper with a checklist, an expanded checklist, an abstract checklist and flow diagram templates. PRISMA tells you what to report, not how to search, so describe any automated retrieval or screening step in your methods clearly enough for readers to judge it. Human reviewers still make the inclusion decisions and still check every extracted finding against the source paper.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.