Skip to content

Medical AI · Generative AI & LLMs · Lesson 1 of 7

How large language models work

Reviewed by Dr. Ram Kumar G, MBBS, MD (Internal Medicine), MPH (USA), on · Last updated

  • Beginner
  • Clinical focus
  • About 25 minutes
  • Includes exercise

Before this lesson: The healthcare-AI landscape: what is in use, what works, and what to ask

In short

A large language model (LLM) generates text one token at a time by predicting what is most likely to come next, based on patterns learned from enormous amounts of text. Further training on instructions and human feedback turns this into a helpful assistant. Because the model optimises for plausible text rather than truth, it can be fluent, knowledgeable and still confidently wrong, which is why clinical use needs grounding, checking and human responsibility.

You will learn to

  • Explain next-token prediction, tokens and temperature in plain terms
  • Describe the stages that turn a pre-trained model into a chat assistant
  • Explain why LLMs produce fluent but false statements
  • Identify the clinical tasks where LLMs are more and less suitable

Predicting the next token

An LLM reads text as tokens: words or pieces of words. Given everything written so far, it calculates a probability for every possible next token, picks one, adds it to the text and repeats. Everything an LLM does, from answering questions to drafting letters, comes from repeating this step.

The settings used to pick tokens matter. 'Temperature' controls how adventurous the choice is: a low temperature almost always picks the most likely token; a higher temperature spreads the choice across less likely ones.

python
import numpy as np

# A made-up model's scores (logits) for the next word after:
# "Metformin is usually first-line treatment for type 2 ..."
candidates = ["diabetes", "patients", "adults", "disease", "hypertension"]
logits = np.array([6.0, 3.5, 2.8, 2.0, 0.5])

def softmax(z, temperature=1.0):
    z = z / temperature
    e = np.exp(z - z.max())
    return e / e.sum()

for t in [0.2, 1.0, 2.0]:
    probs = softmax(logits, t)
    print(f"temperature {t}: " + ", ".join(f"{w} {p:.2f}" for w, p in zip(candidates, probs)))

# temperature 0.2: diabetes 1.00, patients 0.00, adults 0.00, disease 0.00, hypertension 0.00
# temperature 1.0: diabetes 0.87, patients 0.07, adults 0.04, disease 0.02, hypertension 0.00
# temperature 2.0: diabetes 0.59, patients 0.17, adults 0.12, disease 0.08, hypertension 0.04
Invented scores for the next word, and the probabilities at three temperatures.
  • At temperature 0.2 the model is nearly deterministic; at 2.0, 'hypertension' is chosen 4% of the time, producing a statement that is fluent and wrong.
  • Even at low temperature, results can vary between runs and model versions, so outputs used clinically must be checked every time.

From text predictor to assistant

Modern LLMs are built on the transformer architecture, whose attention mechanism lets each token draw on all the others in the text. They are created in stages.

  • The context window is the amount of text the model can consider at once, including your prompt and its answer. Anything outside it is invisible to the model.
  • A model's built-in knowledge stops at its training cut-off date. Newer guidelines, drug approvals or safety warnings are unknown to it unless supplied in the prompt.
StageWhat happensWhat it gives the model
Pre-trainingPredict the next token across a very large collection of textGrammar, facts, reasoning patterns, and the biases and errors present in the text
Instruction tuningFurther training on examples of instructions and good responsesFollows requests, answers in the expected format
Learning from human feedbackPeople (or models) rank responses; the model is tuned toward preferred onesMore helpful, more cautious, but also more eager to please
Deployment featuresSystem prompts, tools, retrieval, safety filtersBehaviour specific to a product or organisation

Why fluent is not the same as true

A toy language model makes the problem visible. The bigram model below learns only which word tends to follow which, from five synthetic sentences, and then generates new ones.

python
import numpy as np
from collections import Counter, defaultdict

corpus = """the patient was started on metformin .
the patient was started on insulin .
the patient was referred to cardiology .
the trial was started in 2019 .
the trial was referred to the ethics committee .""".split("\n")

following = defaultdict(Counter)
for sentence in corpus:
    words = sentence.split()
    for a, b in zip(words, words[1:]):
        following[a][b] += 1

rng = np.random.default_rng(4)
def generate(start="the", max_words=12):
    words = [start]
    while words[-1] != "." and len(words) < max_words:
        options = following[words[-1]]
        probs = np.array(list(options.values())) / sum(options.values())
        words.append(rng.choice(list(options), p=probs))
    return " ".join(words)

for _ in range(5):
    print(generate())

# the ethics committee .
# the patient was started in 2019 .
# the trial was started on insulin .
# the patient was referred to the trial was referred to cardiology .
# the trial was started on insulin .
A bigram model: the simplest possible language model, trained on five sentences.
  • 'The trial was started on insulin' never appeared in the training text. Every word pair is locally plausible, and the sentence is grammatical and false.
  • Real LLMs are vastly more capable and usually stay consistent, but they share the same objective: produce likely text. When the likely continuation and the truth diverge, for example for rare conditions, recent changes or invented references, they can produce confident errors, often called hallucinations.

Where LLMs help and where they struggle

LLMs also reproduce biases from their training text. Studies have found widely used models repeating discredited race-based medical claims (Omiye et al., 2023) and producing differential diagnoses and plans that varied with patients' race and gender (Zack et al., 2024).

Usually more suitableUsually less suitable
Drafting text a clinician will review: letters, summaries, patient informationUnsupervised decisions about diagnosis, dosing or triage
Restructuring information already given: notes into a template, jargon into plain languageQuestions about recent guidelines, approvals or drug safety, unless sources are supplied
Answering from supplied documents, with citations (retrieval-augmented generation)Exact calculations and dose arithmetic, unless a calculator tool is used
Brainstorming differentials or questions to ask, as a prompt for clinical thinkingRare conditions, local practice and populations under-represented in training text

Never paste identifiable patient information into public AI tools

  • Text sent to a public chatbot or API leaves your organisation. Use only tools your organisation has approved for clinical data, under a proper agreement, and follow its rules on what may be entered.
  • All examples in this course use synthetic notes written for teaching.

Exercise

Explore how next-token sampling and temperature create variability and plausible errors, using toy models that run without any API.

Data: Synthetic sentences written in the notebook (no real patient data) (Generated in the notebook)

  1. Reproduce the temperature table and add a 'top-k' sampling rule that only allows the 3 most likely tokens.
  2. Extend the bigram corpus with ten more synthetic sentences and count how many generated sentences are true statements about the corpus.
  3. Change the bigram model to a trigram model (two words of context) and compare how often it produces false combinations.
  4. Optional, with an approved model: ask the same factual question five times at two temperatures and record how the answers vary.

The runnable notebook and worked solution will be published soon. You can work through the steps with the code on this page in the meantime.

Key takeaways

  • LLMs generate text by repeatedly predicting a likely next token.
  • Instruction tuning and human feedback make them helpful, not reliably correct.
  • They know nothing after their training cut-off unless it is supplied.
  • Fluent output can be false; clinical use needs sources, checking and accountability.

Terms used: Context window, Foundation model, Hallucination, Large language model (LLM), Temperature, Token

Related: Prompting for clinical tasks, Medical LLMs and their benchmarks, RAG track: grounding answers in trusted sources

FAQ

Does an LLM understand medicine?

It has learned extensive statistical patterns from medical text and can reason about many problems, but it has no direct access to truth and can produce confident errors. Its output must be checked.

What is a hallucination?

Output that is fluent and confident but false or unsupported, such as an invented reference, a wrong dose or a non-existent guideline.

Why do I get different answers to the same question?

Tokens are sampled from probabilities, so answers vary, especially at higher temperature. Model updates also change answers over time.

What is a context window?

The maximum amount of text, measured in tokens, that the model can consider at once, including the prompt, any documents and its response.

Can I trust an LLM's medical references?

Not without checking. Models can invent plausible-looking references. Systems that retrieve real documents and cite them reduce, but do not remove, this risk.

Educational content only. This material teaches methods; it is not clinical advice. Code, models and examples here are not validated medical devices and must not be used to make decisions about real patients without proper clinical validation, governance and any required regulatory approval. Examples use synthetic or openly licensed de-identified data only. Never paste identifiable patient information into public AI tools. Mentions of models, tools or vendors are for identification, not endorsement.