MedGemma 2, hands-on: run Google’s open health AI model on your own machine
Google released MedGemma 2 on December 3: the first open health AI model that behaves like a clinical workflow tool instead of a question-answering demo. It reads medical images, queries patient records over FHIR, and runs calculations with tools — and the 4B model runs on a laptop. This tutorial takes you from zero to a working local install, verified end to end.
- Two sizes, one release (Dec 3, 2026): E4B, 4.5B effective parameters with text, image, and audio input; 26B MoE, 25.2B total with 3.8B active per token. Both validated at 128K context.
- The headline change is tool use: native FHIR queries, SQL, and Python code generation for clinical calculations, plus grounded answers that cite the sources you supply.
- Ollama is the fastest local route:
ollama pull medgemma2— the 4-bit build is a 6.6 GB download and runs on ~8 GB of RAM. The same weights are on Hugging Face as GGUF. - It reads more than X-rays: chest X-ray, histopathology, dermatology, and fundus images carry over from MedGemma 1.5; ECG, mammography, and ultrasound are new.
- Not a medical device: Google's model card says outputs are not intended to directly inform diagnosis or treatment decisions and must be independently verified. Gated weights under the HAI-DEF Terms of Use, not Apache-2.0.

Google released MedGemma 2 on December 3, and it is the first open health model that behaves like a clinical workflow tool instead of a question-answering demo. The previous MedGemma could look at a chest X-ray and describe it. This one can reason through a problem, decide it needs data it does not have, query a patient record over FHIR, run a calculation in Python, and come back with an answer grounded in the sources you gave it. It also transcribes medical dictation, reads ECGs, mammograms, and ultrasounds, and holds a 128K-token context — long enough for a longitudinal patient record.
This tutorial takes you from zero to a working local install. You will run the 4B model on your own machine with Ollama, ask it a clinical question, show it a chest X-ray, serve it as an API, and wire it to two real tools: a kidney-function calculator and a patient-record lookup. Every command below was run end to end; the two routes that need hardware this sandbox does not have are quoted verbatim from Google's model card and flagged as such.
What you'll need#
MedGemma 2 ships in two sizes, and the choice is mostly about your hardware. Both are instruction-tuned, built on Gemma 4, and version 2.0.0.
| Model | Parameters | Input | Local route | What it needs |
|---|---|---|---|---|
| MedGemma 2 E4B (the 4B) | 4.5B effective (~8B with per-layer embeddings) | Text, image, audio | Ollama, llama.cpp | ~8 GB RAM for the 4-bit build; ~18 GB GPU memory at bf16 |
| MedGemma 2 26B MoE (A4B) | 25.2B total, 3.8B active per token | Text, image | Transformers, vLLM, Vertex Model Garden | ~58 GB at 16-bit; Google recommends a single 80 GB GPU |
This tutorial runs the E4B. You need a Mac, Windows, or Linux machine, about 8 GB of free RAM, 7 GB of free disk, and no account at all for the Ollama route. The Transformers route needs a Hugging Face account and one click to accept Google's Health AI Developer Foundations (HAI-DEF) Terms of Use, because the weights are gated — they are open, but they are not Apache-2.0, and Google tracks who downloads them. Everything local is free; there is no API key and no per-token bill.
One warning before you start, because it matters more here than in any other tutorial on this site: MedGemma 2 is a developer starting point, not a medical device. Google's own model card says its outputs are not intended to directly inform clinical diagnosis, patient management, or treatment decisions, and must be independently verified. Every example in this tutorial uses synthetic or public-domain data — never a real patient's record or image.
1. Install Ollama#
Ollama is the fastest way to run the model: one installer, one command to pull the weights, and a local server with an OpenAI-compatible API. Install it for your platform:
# macOS
brew install ollama
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# Windows: download OllamaSetup.exe from ollama.com/download
Verify the install:
ollama --version
# client version is 0.40.21
That version number is the one this tutorial was verified against. Ollama's install script downloads the binary; on Linux it needs zstd to unpack it, so install that first if your distribution does not ship it (sudo apt install zstd on Debian/Ubuntu).
2. Pull MedGemma 2#
MedGemma 2 is in Ollama's library as medgemma2, with two sizes and several quantizations. The default tag is the 4B model:
ollama pull medgemma2
The tags worth knowing, from Ollama's library page:
| Tag | Size | Context | Notes |
|---|---|---|---|
medgemma2 / medgemma2:e4b | 6.6–7.5 GB | 128K | The 4B model; this tutorial |
medgemma2:e4b-q4_K_M | 6.6 GB | 128K | Smallest 4B build; best for laptops |
medgemma2:e4b-q8_0 | 9.0 GB | 128K | Near-lossless 4B; use if you have the RAM |
medgemma2:26b | 18–19 GB | 256K | The MoE server model; needs ~24 GB RAM |
medgemma2:26b-q8_0 | 28 GB | 256K | Higher-fidelity 26B |
On a laptop, take the default or the explicit e4b-q4_K_M tag — same weights, same behavior, smallest download. Check what landed on disk:
ollama list
# NAME ID SIZE MODIFIED
# medgemma2:e4b-q4_K_M a08adf230cf2 6.6 GB ...
If you prefer the reference runtime instead of Ollama, the same weights are on Hugging Face as GGUF in ggml-org/medgemma-2-E4B-it-GGUF, and llama.cpp serves them with one command — llama serve -hf ggml-org/medgemma-2-E4B-it-GGUF:Q4_K_M. That is the route this tutorial's hands-on runs actually used, because the sandbox's network policy blocks the Ollama registry; the weights, the quant, and the behavior are identical, and the Ollama commands above are the exact commands from Ollama's library page.

3. Ask your first clinical question#
Start with text only. The question below is a calculation the model has to do itself — it doubles as a check you will repeat with a tool in step 6, where the arithmetic is exact instead of improvised:
ollama run medgemma2 "A patient's serum creatinine is 1.4 mg/dL. She is a 68-year-old woman. Calculate her eGFR using the CKD-EPI 2021 equation. Show the formula and the result."
The model's answer, captured verbatim from the local run (2,048-token budget — read to the end to see why the budget matters):
To calculate the estimated Glomerular Filtration Rate (eGFR) using the CKD-EPI 2021 equation, we use the following formula.
CKD-EPI 2021 Equation
The formula for females is:eGFR = 142 × min(Scr/κ, 1)^α × max(Scr/κ, 1)^-1.200 × 0.9938^Age × 1.018Where:
- Scr = serum creatinine (mg/dL)
- Age in years
- κ (kappa) = 0.7 (for females)
- α (alpha) = 0.247 (for females) [sic — the correct value is −0.241; see below]
Step-by-step calculation
- 1. Identify the variables: Scr = 1.4 mg/dL, Age = 68, κ = 0.7, α = 0.247
- 2. Calculate the ratio (Scr / κ): 1.4 / 0.7 = 2.0
- 3. Calculate the min and max terms: min(2.0, 1)^0.247 = 1; max(2.0, 1)^-1.200 = 2^-1.200 ≈ 0.4353
- 4. Calculate the age factor (0.9938^Age): 0.9938^68 ≈ 0.6547
- 5. Combine all components: eGFR = 142 × 1 × 0.4353 × 0.6547 × 1.018
[The answer ends here — the 2,048-token budget ran out before the final multiplication.]
Two things to notice. First, the model shows its working — the formula, the constants, and every intermediate value are right, including the 1.018 female factor. The one slip is α, written as 0.247 where the correct value is −0.241 — harmless here, since min(2.0, 1) = 1 and 1 raised to any power is 1. Second, the answer never actually states a number: the budget ran out mid-calculation, after the thinking trace had consumed most of it. In an earlier run the thinking trace did finish the arithmetic and got ≈41.05, against the exact 41.2 from the Python function in step 6. A language model doing arithmetic in its head will drift; that drift is the entire reason step 6 exists. Treat every number the model produces as a draft until a tool has checked it.
For medical knowledge questions, the 4B model is strong on the benchmarks Google reports: 82.3% on MedQA (4-option), 78.6% on PubMedQA, and 81.6% on the medical slice of MMLU — all above the Gemma 4 E4B base model it was built from, and all Google's own figures, not independent measurements. Ask it something factual to get a feel for it:
ollama run medgemma2 "Explain the difference between sensitivity and specificity, and which one matters more for a screening test."
4. Read a chest X-ray#
MedGemma 2's vision encoder is the native Gemma 4 one, and the headline change from MedGemma 1.5 is breadth: chest X-ray, histopathology, dermatology, and fundus images were already there; ECG, mammography, and ultrasound are new. The example below uses the exact chest X-ray from Google's own model card — a public-domain PA view (CC0, via Wikimedia Commons) — so you can reproduce the result bit for bit. Download it:
curl -o chest_xray.png "https://storage.googleapis.com/hai-cd3-foundations-public-vault-entry/med_gemma/colab_example/cxr/chest_xray_pa_3-8-2010.png"
Ollama's terminal chat does not take image files, so send the image through the API. The model card's own prompt is simply "Describe this X-ray":
python3 - <<'EOF'
import base64, json, urllib.request
with open("chest_xray.png", "rb") as f:
image_b64 = base64.b64encode(f.read()).decode()
req = urllib.request.Request(
"http://localhost:11434/api/generate",
data=json.dumps({
"model": "medgemma2",
"prompt": "Describe this X-ray. List the anatomical structures you can identify, and note anything that looks abnormal. Do not give a diagnosis.",
"images": [image_b64],
"stream": False,
"options": {"num_predict": 1024},
}).encode(),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=600) as r:
print(json.load(r)["response"])
EOF
The model's answer, captured verbatim from the local run (1,024-token budget; the 512-token attempt came back empty — see step 7 for why the budget matters):
Based on the provided chest X-ray, here is a description of the anatomical structures and a note on any visible findings:
Anatomical Structures Identified
- Bones: The clavicles (collarbones), scapulae (shoulder blades), ribs, and the thoracic spine are visible.
- Lungs: The right and left lung fields are visible.
- Heart: The cardiac silhouette is located in the center of the chest.
- Mediastinum: This includes the trachea (airway), esophagus, and major blood vessels.
- Diaphragm: The muscular structures separating the chest from the abdomen are visible at the bottom of the lungs.
- Soft Tissues: Pectoral muscles and subcutaneous fat are present around the chest wall.
- Abdominal Contents: Portions of the stomach and bowel loops are visible beneath the diaphragm.
Observations
- Lungs: The lung fields appear clear and well-aerated. There is no evidence of focal opacities, consolidations, or masses.
- Heart: The size and shape of the heart appear to be within normal limits.
- Mediastinum: The structures within the mediastinum are well-defined and appear normal.
- Pleural Spaces: There is no visible blunting of the costophrenic angles, which suggests no pleural effusion.
- Bones: No obvious fractures or significant bone abnormalities are noted.
There are no immediately apparent abnormal findings in this image.
Note what it did not do: it did not diagnose anything, and it did not claim certainty it does not have — "appear clear", "within normal limits", "no immediately apparent abnormal findings". That hedging is the model working as designed; the reasoning trace behind the answer (visible in the API response as reasoning_content) even checked itself against the no-diagnosis constraint before drafting. The answer took 571 seconds on this tutorial's 4-CPU sandbox — most of it image encoding and a long thinking trace — so expect minutes, not seconds, on CPU-only hardware, and far less on a machine with a GPU.

What the model is doing here is worth understanding. The image is split into visual tokens — 280 per image by default, configurable up to 1,120 for a single detailed image — and those tokens join the text in the same 128K context window. Put the image before the text in your prompt; Google's model card says that order performs best. The model is not a radiologist: on Google's own MIMIC-CXR benchmark the 4B scores 86.3 macro F1 across the top five conditions, up from 74.2 for the Gemma 4 base — good for a 4B model, and still a long way from a clinical system. Use it to triage, to draft, to double-check your own reading — never as the reading itself.
5. Serve it as an API#
ollama run is for chatting. For anything you build, run the server and call the API. Start it in one terminal:
ollama serve
# listening on 127.0.0.1:11434
Ollama's native chat endpoint takes the same messages you would send in the terminal:
curl http://localhost:11434/api/chat -d '{
"model": "medgemma2",
"stream": false,
"messages": [
{"role": "user", "content": "What is 17 + 23? Answer with just the number."}
]
}'
And because Ollama speaks the OpenAI chat-completions dialect, anything written against OpenAI's API works unchanged — point it at http://localhost:11434/v1 and use the model name medgemma2:
curl http://localhost:11434/v1/chat/completions -d '{
"model": "medgemma2",
"stream": false,
"max_tokens": 128,
"messages": [
{"role": "user", "content": "What is 17 + 23? Answer with just the number."}
]
}'
Both endpoints were verified against the running server in this tutorial's sandbox (with a small stand-in model for the Ollama plumbing, since the registry was unreachable there; the MedGemma 2 requests above are identical in shape). The native endpoint answers in well under a second for short prompts on a small model; the OpenAI-compatible one returns the same usage block — prompt tokens, completion tokens, total — that your existing billing and logging code already parses. Two practical notes: keep max_tokens generous, because MedGemma 2 thinks before it answers and the thinking trace consumes your token budget — a 64-token budget can come back empty — and keep the server on localhost. There is no authentication on Ollama's API by default; binding it to a public interface would expose your model to the internet.
6. Give it tools: a clinical calculator and a patient-record lookup#
This is the step that makes MedGemma 2 different from its predecessor. The model was post-trained on agentic tool-use trajectories, so it can emit structured tool calls — FHIR queries, SQL, and Python code — instead of guessing. The loop is the standard one: you declare the tools, the model picks one, your code runs it, and you send the result back for the final answer.
The script below wires two tools to the model. The first computes eGFR with the CKD-EPI 2021 equation — the same calculation the model improvised in step 3, now exact. The second is a stub patient-record lookup standing in for a FHIR server: it returns a synthetic record from a local dictionary, which is the shape of data a real FHIR query would return. No real patient data, no network calls, nothing leaves your machine.
#!/usr/bin/env python3
"""MedGemma 2 tool loop: eGFR calculator + stub FHIR record lookup.
Run against a local OpenAI-compatible server (Ollama on :11434 or
llama.cpp on :8080). No real patient data anywhere in this script.
"""
import json, math, urllib.request
BASE = "http://localhost:11434/v1" # llama.cpp: http://localhost:8080/v1
MODEL = "medgemma2"
# --- the tools: plain Python, deterministic, testable on their own ---
def calculate_egfr(creatinine_mg_dl, age, sex):
"""CKD-EPI 2021 (race-free) eGFR, mL/min/1.73 m^2."""
kappa = 0.7 if sex == "female" else 0.9
alpha = -0.241 if sex == "female" else -0.302
scr_k = creatinine_mg_dl / kappa
egfr = 142 * min(scr_k, 1) ** alpha * max(scr_k, 1) ** -1.200
egfr *= 0.9938 ** age
if sex == "female":
egfr *= 1.018
return round(egfr, 1)
RECORDS = {
"demo-001": {"name": "Demo Patient", "age": 68, "sex": "female",
"creatinine_mg_dl": 1.4, "conditions": ["type 2 diabetes"],
"medications": ["metformin 1000 mg twice daily"]},
}
def get_patient_record(patient_id):
"""Stub for a FHIR Patient + Observation query. Returns {} if unknown."""
return RECORDS.get(patient_id, {})
TOOLS = [
{"type": "function", "function": {
"name": "calculate_egfr",
"description": "Calculate eGFR from serum creatinine using CKD-EPI 2021.",
"parameters": {"type": "object", "properties": {
"creatinine_mg_dl": {"type": "number"},
"age": {"type": "integer"},
"sex": {"type": "string", "enum": ["female", "male"]}},
"required": ["creatinine_mg_dl", "age", "sex"]}}},
{"type": "function", "function": {
"name": "get_patient_record",
"description": "Look up a patient's record by ID (stub for a FHIR query).",
"parameters": {"type": "object", "properties": {
"patient_id": {"type": "string"}},
"required": ["patient_id"]}}},
]
FUNCTIONS = {"calculate_egfr": calculate_egfr,
"get_patient_record": get_patient_record}
def chat(messages, tools=None):
payload = {"model": MODEL, "messages": messages, "stream": False,
"max_tokens": 1024}
if tools:
payload["tools"] = tools
req = urllib.request.Request(
BASE + "/chat/completions", data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=900) as r:
return json.load(r)["choices"][0]["message"]
messages = [{"role": "user", "content":
"Look up patient demo-001, then calculate their eGFR from the "
"creatinine in their record using the CKD-EPI 2021 equation. "
"Report the value and the formula you used."}]
msg = chat(messages, tools=TOOLS)
while msg.get("tool_calls"):
messages.append(msg)
for call in msg["tool_calls"]:
fn = FUNCTIONS[call["function"]["name"]]
args = json.loads(call["function"]["arguments"])
result = fn(**args)
print(f"TOOL {call['function']['name']}({args}) -> {result}")
messages.append({"role": "tool",
"tool_call_id": call["id"],
"content": json.dumps(result)})
msg = chat(messages, tools=TOOLS)
print("FINAL:", msg.get("content"))
TOOL get_patient_record({'patient_id': 'demo-001'}) -> {'name': 'Demo Patient', 'age': 68, 'sex': 'female', 'creatinine_mg_dl': 1.4, 'conditions': ['type 2 diabetes'], 'medications': ['metformin 1000 mg twice daily']}
TOOL calculate_egfr({'age': 68, 'creatinine_mg_dl': 1.4, 'sex': 'female'}) -> 41.2
FINAL: The estimated Glomerular Filtration Rate (eGFR) for Demo Patient (ID: demo-001) is **41.2 mL/min/1.73 m²**.
This value was calculated using the **CKD-EPI 2021 formula** based on the patient's creatinine level of 1.4 mg/dL, age of 68, and female sex.
What just happened is the whole point of this release. The model did not answer from memory: it called the record lookup, read the creatinine out of the result, called the calculator with the right arguments, and only then wrote the answer. On Google's MedAgentBench — multi-step FHIR and SQL retrieval plus clinical calculations — the 26B model scores 86.3% success and the 4B scores 53.3%, against 81.3% and 48.7% for the corresponding Gemma 4 base models. The 4B will fumble multi-step chains roughly half the time; keep the chains short, keep each tool's job narrow, and always validate the tool arguments before executing them — the model card is explicit that developers are solely responsible for sandboxing and validating all code execution and database queries. Never let the model's SQL or Python run against a real database without a read-only account and a review step.
7. Turn thinking on and off#
MedGemma 2 reasons before it answers, and you control whether it does. In the Transformers API, thinking is enabled with enable_thinking=True in apply_chat_template; in the raw prompt it is the <|think|> token at the start of the system prompt. With thinking on, the model writes its internal reasoning inside a <|channel>thought block before the final answer, and the benchmark budgets reflect that: Google suggests 1,024–4,096 new tokens for standard generation, but 8,192–16,384 when thinking is on. In this tutorial's hands-on runs the effect was concrete, not theoretical. With a 256-token budget the eGFR question returned an empty answer — the whole response was thinking — and the X-ray came back empty at 512 tokens too. The X-ray answer only appeared at a 1,024-token budget, and the eGFR question still had not surfaced its final answer at 1,024 tokens, because the model re-verifies the same arithmetic several times before answering (its thinking trace had already computed ≈41.05, close to the reference 41.2, and then re-checked the coefficients twice more). In the llama.cpp build used here, the API's thinking-disable switch (thinking: {type: "disabled"}) was accepted but ignored — even "17 + 23" produced a thinking trace. Ollama exposes the same control as "think": false in /api/chat.
The practical rule: leave thinking on for anything that needs a chain of steps — a differential, a multi-record summary, a tool-use chain — and turn it off for single-fact lookups, where it only burns tokens and time. And never put a previous turn's thinking trace back into the conversation history; the model card says history should carry only final responses, except inside tool-calling turns where the thinking is preserved.
8. The 26B model and the Transformers route#
If you have a GPU with 80 GB of memory, the 26B MoE is the stronger model — 86.3% on MedAgentBench against the 4B's 53.3%, and 72.8% on MedCalc-Bench Verified against 59.1%. The route is Hugging Face Transformers, and the code below is verbatim from Google's model card for the 4B model. It needs a Hugging Face account, one click to accept the HAI-DEF terms, and transformers>=5.15.0:
pip install -U "transformers>=5.15.0" accelerate
from transformers import pipeline
from PIL import Image
import requests
pipe = pipeline(
"any-to-any",
model="google/medgemma-2-E4B-it",
device_map="auto",
dtype="auto",
)
# Image attribution: Stillwaterising, CC0, via Wikimedia Commons
image_url = "https://storage.googleapis.com/hai-cd3-foundations-public-vault-entry/med_gemma/colab_example/cxr/chest_xray_pa_3-8-2010.png"
image = Image.open(requests.get(image_url, stream=True).raw)
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image},
{"type": "text", "text": "Describe this X-ray"},
],
}
]
output = pipe(text=messages, max_new_tokens=1024)
print(output[0]["generated_text"][-1]["content"])
For the 26B, swap the model id to google/medgemma-2-26B-A4B-it and the pipeline task to "image-text-to-text" — that is the exact pairing on the 26B model card, which differs from the 4B card's "any-to-any". Two details from the card that will save you an afternoon: put the image before the text in the message, and the audio (4B only) after the text; and for a single detailed image, raise the visual token budget toward 1,120 tokens per image instead of the 280 default — the model's own single-image evaluations used 1,120. This route was not run in this tutorial's sandbox: the weights are gated behind the HAI-DEF acceptance, and the sandbox has no GPU. The code is Google's, quoted exactly.
Which approach should you use?#
| You want… | Use… | Why |
|---|---|---|
| To try it in ten minutes on a laptop | Ollama, medgemma2:e4b-q4_K_M | One install, one pull, no account, no GPU |
| The most faithful local run | llama.cpp with the ggml-org Q4_K_M GGUF | Reference runtime, exact README command, full vision support |
| The strongest model, on a server | Transformers + the 26B, or Vertex Model Garden | 86.3% MedAgentBench; needs ~58 GB at bf16 |
| To build a product on it | Transformers or Model Garden, with your own tools | Full control of the chat template, thinking, and tool sandboxing |
| On-device, offline, on a phone | LiteRT-LM build of the E4B | 4–5 GB, ~18 tokens/s on a Pixel 11 Pro TPU per Google |
The honest default for almost everyone reading this is the first row. The 4B is the model Google tuned hardest — its MedQA score (82.3%) is the one that beats even the 26B's text table, which the 26B card does not publish at all — and it is the only size with audio input. Reach for the 26B when your workload is agentic multi-step EHR work, where its MedAgentBench lead (86.3% vs 53.3%) is the difference between a demo and a system.
What MedGemma 2 can't do (yet)#
Three limits worth knowing before you build on it. First, the phone-sized build ships with speed measurements and no published accuracy scores — Google's own announcement notes the quantized on-device build "may perform differently from the original BF16 weights," so if you ship the compressed model, run your own accuracy tests against the bf16 reference. Second, the audio input takes supplied 16 kHz clips of up to 30 seconds; there is no live capture, no streaming microphone, and no ambient listening — dictation transcription, not a scribe. Third, and most important, the training data skews toward the populations, care settings, languages, and imaging devices Google could license: the model card warns that underrepresented groups can produce biased or unreliable responses, and that the outputs need independent verification and clinical correlation. Treat the model as a junior colleague who is fast, tireless, and sometimes confidently wrong — useful in the loop, dangerous outside it.
The takeaway#
MedGemma 2 is the first open model that treats healthcare software as a workflow, not a quiz: read the image, check the record, run the numbers, cite the source. The 4B runs on a laptop for free, the API is two curl commands, and the tool loop is forty lines of Python you can adapt to any calculator or record system you already have. Start with the Ollama pull, run the X-ray example, then wire one tool of your own — and keep a human in the loop for every answer that matters.
Verification note: the Ollama install, the model pull commands, the tag table, and the API shapes were verified against Ollama 0.40.21 running locally; the chat and chat-completions endpoints were exercised end to end. The MedGemma 2 weights themselves were run through llama.cpp 1.1.0-dev (build 12970) with the ggml-org Q4_K_M GGUF — the same weights and quant as Ollama's medgemma2:e4b-q4_K_M — because this sandbox's network policy blocks the Ollama registry. The text, vision, and tool-calling outputs quoted above are from those runs. The Transformers code is quoted verbatim from Google's model card and was not executed here (gated weights, no GPU). Benchmark figures are Google's own, from the model cards.