You can now run a medical model that reads chest X-rays and queries FHIR records on your own server. Google released MedGemma 2 on December 3, 2026, Ollama listed both sizes the same day, and no patient record has to leave your network to use it. We pulled the MedGemma 2 Ollama tags onto an RTX 4090 and a CPU-only Ubuntu box, and the first surprise was speed. The 26B model generated 159 tokens per second against 163 for the small E4B, because only about 4 billion of its parameters work on each token.
This guide installs Ollama on Ubuntu, pulls both models, and measures VRAM and tokens per second on GPU and CPU. You then test both sizes on a real chest X-ray and wire MedGemma 2 tool calling to a local HAPI FHIR server loaded with Synthea synthetic patients. I ran through all of it in December 2026 on Ubuntu 26.04 and a 24 GB RTX 4090, re-checked the install steps on 24.04, and it works end to end.
MedGemma 2 E4B vs 26B: which size to run
Run the 26B if you have a 24 GB GPU, and the E4B everywhere else. MedGemma 2 is the Google health model family built on Gemma 4. You get native tool calling, grounded answers with citations, and support for 2D medical images across radiology, dermatology, ophthalmology and pathology (the MedGemma 2 model card has the full list). It ships in two sizes: E4B is a dense model of about 8 billion parameters (4.5 billion effective) that also takes audio, and 26B A4B is a mixture-of-experts model of 25.2 billion parameters with about 3.8 billion active per token.
We measured both Ollama builds (Q4_K_M) with the same prompt, three timed runs each on the GPU and two on CPU after a warm-up, because the first run after a load always reads slow. The table holds the median GPU run and the mean CPU run, plus the X-ray result from Step 5, so you can weigh speed against accuracy in one place.
| Measured | medgemma2:e4b | medgemma2:26b |
|---|---|---|
| Download size | 6.6 GB | 18 GB |
| VRAM used, 32K context (RTX 4090, nvidia-smi) | 5.5 GiB | 19.2 GiB |
| VRAM used, 128K context (RTX 4090, nvidia-smi) | 6.9 GiB | 21.1 GiB |
| Generation speed, RTX 4090 | 163 tokens/s | 159 tokens/s |
| Generation speed, CPU only, 32 threads of an AMD EPYC 7B12 (2 runs) | 20.3 tokens/s | 20.3 tokens/s |
| Generation speed, CPU only, 8 vCPU Intel Xeon VM (2 runs) | 7.5 tokens/s | 7.1 tokens/s |
| RAM used on CPU | 6.1 GB | 18 GB |
| Context window | 128K | 256K (validated at 128K) |
| Chest X-ray test, 3 runs each | Heart size wrong in 3 of 3 | Heart failure found in 3 of 3 |
Speed follows active parameters, not file size, so the two models land within a few percent of each other on both the GPU and the 32-thread CPU. What you trade is quality against memory. The 26B read our test X-ray correctly in every run, while the E4B called an enlarged heart normal three times out of three, so the extra 14 GiB of VRAM buys accuracy without costing you speed. Google quotes 80 GB GPUs for the 26B and 24 GB for the E4B, but that is for the full bfloat16 weights. The 4-bit Ollama builds fit the 26B on a single 24 GB card with room for the whole 128K context.
For MedGemma 2 measured against plain Gemma 4 and MedGemma 1.5 on the same RTX 4090 (medical exam questions, chest X-ray, FHIR tool calls, VRAM and speed), see our MedGemma 2 vs Gemma 4 benchmark.
So should you buy a bigger GPU for MedGemma 2? Only up to 24 GB, because that is the line where the better model fits. Our GPU picks by VRAM and model size cover that tier. If your budget stops lower, the 12 GB and 16 GB cards under $500 run the E4B with plenty of headroom. When the box has to sit quietly in a clinic office rather than a rack, a mini PC with unified memory is the option to look at.
Prerequisites
The model you pick decides the memory, and the FHIR lab adds a little on top of that:
- Ubuntu 26.04 or 24.04 server with sudo access
- For E4B: 8 GB of VRAM, or 16 GB of RAM for CPU only
- For 26B: a 24 GB GPU, or 32 GB of RAM for CPU only
- 40 GB of free disk for both models, Docker images and Synthea
- Outbound HTTPS to ollama.com, Docker Hub, ghcr.io and GitHub
Those figures are what this lab needed to follow along, not a sizing for a hospital workload. Memory grows with the context window you set (the 26B went from 19.2 GiB to 21.1 GiB of VRAM between 32K and 128K), and concurrency multiplies it, because every parallel request carries its own context. If several clinicians will query it at once, size for the context you need times the parallel requests, and test that before you buy. Ollama, HAPI FHIR and Open WebUI all bind to localhost in this guide, so no firewall ports need opening.
Step 1: Install Ollama on Ubuntu
Ollama ships an install script that sets up the binary, an ollama system user and a systemd service. It downloads a .tar.zst archive, and on a minimal Ubuntu image it stops with “This version requires zstd for extraction” unless zstd is installed first, so we add it before running the script:
sudo apt-get update
sudo apt-get install -y zstd
curl -fsSL https://ollama.com/install.sh | sh
On a machine with an NVIDIA card the script reports the GPU it found. Our Ubuntu 26.04 VM had none, so it ended with a CPU-only warning and still started the service:
>>> Creating ollama systemd service...
>>> Enabling and starting ollama service...
Created symlink '/etc/systemd/system/default.target.wants/ollama.service' → '/etc/systemd/system/ollama.service'.
>>> The Ollama API is now available at 127.0.0.1:11434.
>>> Install complete. Run "ollama" from the command line.
WARNING: No NVIDIA/AMD GPU detected. Ollama will run in CPU-only mode.
Confirm the service is running and check the version, because the MedGemma 2 tags need a current Ollama release.
systemctl is-active ollama
ollama --version
You want active and a version string. MedGemma 2 uses the Gemma 4 renderer, so stay on a current Ollama release, and rerun the same install script whenever you need to upgrade:
active
ollama version is 0.40.19
If you also want Ollama reachable from other machines behind Nginx and TLS, the full Ollama install walkthrough for Ubuntu 26.04 covers that part. For patient-adjacent work we keep it on localhost.
Step 2: Pull the MedGemma 2 Ollama models
Ollama publishes the family as medgemma2, with e4b as the default tag and 26b for the mixture-of-experts model. Pull the one your hardware fits, or both if you want to compare them the way we did:
ollama pull medgemma2:e4b
ollama pull medgemma2:26b
The 18 GB download is the slow part of this step, and on our GPU host it ran at about 360 MB/s. List the models and inspect the 26B.
ollama list
ollama show medgemma2:26b
Read the capabilities block first. The 26B lists vision, tools and thinking, and thinking is on by default, which matters later because a thinking model spends hundreds of tokens before it answers.
NAME ID SIZE MODIFIED
medgemma2:26b 7c9577954411 18 GB 30 minutes ago
medgemma2:e4b a08adf230cf2 6.6 GB 31 minutes ago
Model
architecture gemma4
parameters 25.2B
context length 262144
embedding length 2816
quantization Q4_K_M
renderer gemma4-large
parser gemma4
template source renderer_parser
Capabilities
completion
vision
tools
thinking
levels false, true
default true
Run the same command on the E4B and you get the same list plus audio, since only the small model takes sound. Both ship with the sampling the model card recommends (temperature 1.0, top-k 64, top-p 0.95), so you do not need to set those yourself. For how these two compare with other local models at the same VRAM, the Ollama models cheat sheet lists them by memory tier.
Step 3: Raise the context window
Ollama sizes the default context from VRAM: 4K tokens under 24 GB, 32K from 24 to 48 GB, and 256K above that, per the Ollama context length docs. On our RTX 4090 the models loaded with 32K, but on the CPU-only VM ollama ps showed 4096, which is too small once a tool loop starts feeding FHIR results back to the model. Set it in a systemd drop-in so it survives upgrades of the unit file:
sudo mkdir -p /etc/systemd/system/ollama.service.d
printf "[Service]\nEnvironment=\"OLLAMA_CONTEXT_LENGTH=32768\"\n" | sudo tee /etc/systemd/system/ollama.service.d/context.conf
sudo systemctl daemon-reload
sudo systemctl restart ollama
Load a model and check the CONTEXT column, since that is the value Ollama actually gave the model rather than the one you asked for.
ollama run medgemma2:e4b "Say ready." --hidethinking
ollama ps
Now the model holds 32768 tokens on the CPU box.
ready
NAME ID SIZE PROCESSOR CONTEXT RUNNER UNTIL
medgemma2:e4b a08adf230cf2 6.1 GB 100% CPU 32768 llamacpp 4 minutes from now
A 24 GB GPU already gets 32K, and both sizes fit 128K on it (the table above has the VRAM), so raise the value to 131072 there if you plan to feed long patient histories. We measured the memory at 128K, not the speed with a full 128K prompt, so expect generation to slow as the context fills.
Step 4: Run a prompt and measure speed
The --verbose flag prints timing after the answer, and the eval rate line is the generation speed you feel while reading. This is the prompt we used for every number in this guide:
ollama run medgemma2:26b --verbose "A 67-year-old man with type 2 diabetes has a serum creatinine of 1.4 mg/dL. In five short bullet points, explain what eGFR measures and why it matters for metformin dosing."
MedGemma 2 thinks first, prints its reasoning, then answers. On the RTX 4090 the answer and timing ended like this.
...done thinking.
Here is an explanation of eGFR and its role in metformin dosing:
* **Definition:** eGFR (estimated Glomerular Filtration Rate) estimates how well the kidneys are filtering waste and excess fluid from the blood.
* **Accuracy:** It combines serum creatinine with age, sex, and body size to provide a more accurate assessment of kidney function than creatinine alone.
* **Metformin Clearance:** Because metformin is excreted almost entirely by the kidneys, a low eGFR means the body cannot clear the drug efficiently.
* **Safety Risk:** If eGFR is too low, metformin can accumulate in the bloodstream, significantly increasing the risk of a rare but life-threatening condition called lactic acidosis.
* **Dosing Guidance:** Clinical guidelines use specific eGFR thresholds (typically <45 or <30 mL/min/1.73 m²) to determine whether to reduce the metformin dose or discontinue it entirely.
total duration: 5.517608501s
load duration: 1.129746ms
prompt eval count: 62 token(s)
prompt eval cached: 57 token(s)
prompt eval duration: 35.779ms
prompt eval rate: 139.75 tokens/s
eval count: 854 token(s)
eval duration: 5.387183s
eval rate: 158.52 tokens/s
That is 854 tokens in about five seconds, most of them reasoning. While the model is loaded, check where it landed and how much memory it took:
ollama ps
nvidia-smi
Check that the PROCESSOR column says 100% GPU. A split such as 30%/70% CPU/GPU means the model or its context did not fit, and generation drops to CPU speed for the offloaded layers. With the 26B loaded at 32K context, the card showed 19,581 MiB of 24,564 MiB in use:
NAME ID SIZE PROCESSOR CONTEXT RUNNER UNTIL
medgemma2:26b 7c9577954411 18 GB 100% GPU 32768 llamacpp 4 minutes from now
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 595.112.13 Driver Version: 595.112.13 CUDA Version: 13.2 |
+-----------------------------------------+------------------------+----------------------+
| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|=========================================+========================+======================|
| 0 NVIDIA GeForce RTX 4090 On | 00000000:81:00.0 Off | Off |
| 0% 47C P2 97W / 450W | 19581MiB / 24564MiB | 56% Default |
| | | N/A |
+-----------------------------------------+------------------------+----------------------+
Right after the answer the card drew 97 W of its 450 W limit, with about 5 GB of VRAM still free. For this model a 24 GB card is about capacity first, because the 26B needs roughly 19 GiB at 32K context and any 24 GB card holds it. We only measured the 4090, so treat its 159 tokens per second as the top of the range rather than what a slower 24 GB card will reach.
Step 5: Test MedGemma 2 on a chest X-ray
Image input is where the two sizes split hardest. We used a de-identified frontal chest radiograph that its author, Mikael Häggström, released into the public domain under CC0 on Wikimedia Commons. The file description gives the ground truth: an 83-year-old man after coronary bypass surgery, with Kerley B lines, an enlarged heart, dilated pulmonary vessels and a minor pleural effusion, which is a picture of heart failure.

Wikimedia answered our first wget with 429 Too Many Requests and a request with a placeholder contact with 403, because its servers reject generic and fake user agents. A descriptive user agent that points at a real page works:
curl -fsSL -A "medgemma-lab/1.0 (https://computingforgeeks.com/)" -o chest-xray-kerley-b-lines.jpg https://upload.wikimedia.org/wikipedia/commons/c/ca/Chest_radiograph_of_a_lung_with_Kerley_B_lines.jpg
Ollama attaches an image when you put its path inside the prompt. We hid the reasoning with --hidethinking to keep the output short:
ollama run medgemma2:26b --hidethinking --verbose "You are reviewing a de-identified frontal chest radiograph for a teaching exercise. Describe the key findings in a short structured report (devices, heart size, lungs, pleura), then give an impression. ./chest-xray-kerley-b-lines.jpg"
The 26B found the sternotomy wires, the enlarged heart, the edema and the effusions, and reached the right diagnosis. It did not name the Kerley B lines or the dilated vessels, which a radiologist would.
**Findings:**
* **Devices:** Median sternotomy wires are present.
* **Heart size:** Cardiomegaly is present.
* **Lungs:** There is diffuse bilateral interstitial opacification and pulmonary edema, more prominent in the lower lung zones. Lung volumes are low.
* **Pleura:** Small to moderate bilateral pleural effusions are present, causing blunting of the costophrenic angles.
**Impression:**
Cardiomegaly with pulmonary edema and bilateral pleural effusions, most consistent with congestive heart failure.
prompt eval count: 542 token(s)
prompt eval rate: 32.85 tokens/s
eval count: 578 token(s)
eval rate: 156.71 tokens/s
Swap medgemma2:26b for medgemma2:e4b in the same command and the small model reports a pacemaker that is not there and calls the film normal:
**Devices:** A right-sided pacemaker/ICD generator is visible in the right pectoral region, with leads extending into the right atrium and right ventricle.
**Heart Size:** Normal.
**Lungs:** Clear. There is no evidence of focal consolidation, pulmonary edema, or pneumothorax.
**Pleura:** No pleural effusion.
**Impression:** Right-sided pacemaker. No other acute cardiopulmonary process.
prompt eval count: 634 token(s)
prompt eval rate: 1243.78 tokens/s
eval count: 537 token(s)
eval rate: 159.85 tokens/s
One run proves little at temperature 1.0, so we repeated it. The E4B described a central venous catheter on the second run. On the third it finally saw the sternal wires, yet it called the heart size normal all three times. The 26B named the sternotomy wires and cardiomegaly and reached heart failure on all three runs, the third of them on the CPU-only VM with the same quantized model. Treat the E4B as a text and tool-calling model for hardware that cannot hold the 26B, and do not trust it to read images. That matches the model card, which warns that quantized builds “may perform differently from the original BF16 weights and should be validated separately”.
Step 6: Start HAPI FHIR with Synthea synthetic patients
Tool calling needs something to call, and in healthcare that is usually a FHIR server. We run HAPI FHIR in Docker and fill it with patients generated by Synthea, so every record below is synthetic and no real patient is involved. Install Docker and Java 21 for Synthea from the Ubuntu archive:
sudo apt-get install -y docker.io openjdk-21-jre-headless
Start HAPI FHIR bound to localhost only, on its default port 8080. Binding to 127.0.0.1 keeps the server off the network, so only processes on this box, such as the tool-calling script in Step 7, can query it.
sudo docker run -d --name hapi-fhir --restart unless-stopped -p 127.0.0.1:8080:8080 hapiproject/hapi:latest
Give the server about a minute to start. Its capability statement answers once it is up.
curl -s http://localhost:8080/fhir/metadata | python3 -c "import sys,json;d=json.load(sys.stdin);print(d['fhirVersion'], d['software']['name'], d['software']['version'])"
FHIR version 4.0.1 means R4, which is what Synthea exports by default.
4.0.1 HAPI FHIR Server 9.0.0
Download the latest Synthea release jar and generate 25 patients. The -s 42 seed keeps the population repeatable for a given Synthea release, but Synthea dates everything relative to today, so ages and lab dates will shift from ours. Turning off the US Core profile keeps the bundles plain R4 that HAPI accepts without extra packages:
mkdir -p ~/synthea && cd ~/synthea
curl -sSL -o synthea-with-dependencies.jar https://github.com/synthetichealth/synthea/releases/latest/download/synthea-with-dependencies.jar
java -jar synthea-with-dependencies.jar -p 25 -s 42 --exporter.fhir.use_us_core_ig false Massachusetts
Synthea counts living patients against -p and keeps the deceased ones it simulated along the way, so 25 became 29:
You've just generated 29 patients! We're happy to know Synthea is helping you with your project.
Each patient is a FHIR transaction bundle in output/fhir. The patient bundles reference hospitals and clinicians defined in two shared files, so those two go in first, then every patient:
cd ~/synthea/output/fhir
for f in hospitalInformation*.json practitionerInformation*.json; do curl -s -o /dev/null -w "%{http_code} $f\n" -X POST -H "Content-Type: application/fhir+json" --data-binary @"$f" http://localhost:8080/fhir; done
for f in $(ls | grep -vE "^(hospital|practitioner)"); do curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/fhir+json" --data-binary @"$f" http://localhost:8080/fhir; done | sort | uniq -c
Every bundle should return HTTP 200. The 29 patient bundles took 91 seconds on the 8 vCPU VM:
200 hospitalInformation1796320108009.json
200 practitionerInformation1796320108009.json
29 200
Count the patients to confirm the load.
curl -s "http://localhost:8080/fhir/Patient?_summary=count"
Compare the total field with the number Synthea printed. A lower count means a bundle failed, and the status codes from the loop show you which one.
{
"resourceType": "Bundle",
"id": "89169f15-98e6-4677-b224-8c0bfc5a1916",
"meta": {
"lastUpdated": "2026-12-03T18:30:00.518+00:00",
"tag": [ {
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationValue",
"code": "SUBSETTED",
"display": "Resource encoded in summary mode"
} ]
},
"type": "searchset",
"total": 29
}
The default question in the next step looks for Tremblay, a patient with chronic kidney disease in our run. List the family names in yours, so you know which one to ask about:
curl -s "http://localhost:8080/fhir/Patient?_count=50&_elements=name" | python3 -c "import sys,json; print(sorted(e['resource']['name'][0]['family'] for e in json.load(sys.stdin)['entry']))"
Our run produced these 29 names, with the numeric suffix Synthea adds to keep them unique:
['Aufderhar910', 'Bosco882', 'Botsford977', 'Braun514', 'Carroll471', 'Casper496', 'Effertz744', 'Fay398', 'Fritsch593', 'Gorczany269', 'Grimes165', 'Hagenes547', 'Hagenes547', 'Hammes673', 'Harber290', 'Hickle134', 'Kozey370', 'Luettgen772', 'Mayert710', 'Mertz280', 'Monahan736', 'Montero62', 'Nader710', 'Ortiz186', 'Price929', 'Rosenbaum794', 'Tremblay80', 'Walter473', 'Zieme486']
Treat this container as a lab fixture. The default hapiproject/hapi image stores everything in an in-memory H2 database (its startup log shows jdbc:h2:mem:test_mem), so a container restart empties the server and you reload the bundles. That is fine for a lab and wrong for anything else.
Step 7: Let MedGemma 2 call FHIR tools
The Ollama /api/chat endpoint takes a tools list of JSON schemas. When the model wants data it answers with tool_calls instead of text, our script runs the matching Python function against FHIR, appends the result as a tool message, and asks again until the model answers. The script uses only the Python standard library, so there is nothing to install. It gives MedGemma 2 four tools:
search_patientsfinds a patient by nameget_conditionslists active conditionsget_observationsreturns the latest results for one LOINC codeegfr_ckd_epi_2021computes eGFR and the KDIGO stage in Python
Create the script in your home directory, which is where the run commands below expect it.
vim ~/fhir_agent.py
Paste the full script. The model name and the question are arguments, with medgemma2:e4b and a kidney function question as defaults:
#!/usr/bin/env python3
"""Let MedGemma 2 query a local FHIR server through Ollama tool calling."""
import json
import sys
import urllib.parse
import urllib.request
from datetime import date
OLLAMA = "http://localhost:11434/api/chat"
FHIR = "http://localhost:8080/fhir"
MODEL = sys.argv[1] if len(sys.argv) > 1 else "medgemma2:e4b"
QUESTION = sys.argv[2] if len(sys.argv) > 2 else (
"Find the patient named Tremblay. Get their most recent serum creatinine "
"(LOINC 2160-0), then calculate eGFR with the CKD-EPI 2021 equation and "
"say which CKD stage that falls in. List their active conditions that matter "
"for kidney function."
)
def fhir_get(path, params):
url = f"{FHIR}/{path}?{urllib.parse.urlencode(params)}"
with urllib.request.urlopen(url, timeout=30) as r:
return json.load(r)
def search_patients(name):
b = fhir_get("Patient", {"name": name, "_count": 5})
return [{
"id": e["resource"]["id"],
"name": " ".join(e["resource"]["name"][0].get("given", []) + [e["resource"]["name"][0].get("family", "")]),
"gender": e["resource"].get("gender"),
"birthDate": e["resource"].get("birthDate"),
} for e in b.get("entry", [])]
def get_conditions(patient_id):
b = fhir_get("Condition", {"patient": patient_id, "clinical-status": "active", "_count": 50})
return sorted({e["resource"]["code"]["coding"][0]["display"] for e in b.get("entry", [])})
def get_observations(patient_id, loinc_code):
b = fhir_get("Observation", {"patient": patient_id, "code": f"http://loinc.org|{loinc_code}",
"_sort": "-date", "_count": 3})
out = []
for e in b.get("entry", []):
o = e["resource"]
q = o.get("valueQuantity", {})
out.append({"date": o.get("effectiveDateTime"), "value": q.get("value"), "unit": q.get("unit")})
return out
def egfr_ckd_epi_2021(creatinine_mg_dl, sex, birth_date, on_date):
scr, female = float(creatinine_mg_dl), sex.lower().startswith("f")
born, on = date.fromisoformat(birth_date[:10]), date.fromisoformat(on_date[:10])
age = on.year - born.year - ((on.month, on.day) < (born.month, born.day))
k, a = (0.7, -0.241) if female else (0.9, -0.302)
egfr = 142 * min(scr / k, 1) ** a * max(scr / k, 1) ** -1.200 * 0.9938 ** age * (1.012 if female else 1)
stage = next(s for lim, s in [(90, "G1"), (60, "G2"), (45, "G3a"), (30, "G3b"), (15, "G4"), (0, "G5")] if egfr >= lim)
return {"age": age, "egfr": round(egfr, 1), "unit": "mL/min/1.73m2", "stage": stage}
TOOLS = {"search_patients": search_patients, "get_conditions": get_conditions,
"get_observations": get_observations, "egfr_ckd_epi_2021": egfr_ckd_epi_2021}
SCHEMAS = [
{"type": "function", "function": {
"name": "search_patients", "description": "Search the FHIR server for patients by name.",
"parameters": {"type": "object", "required": ["name"],
"properties": {"name": {"type": "string", "description": "Family or given name"}}}}},
{"type": "function", "function": {
"name": "get_conditions", "description": "List a patient's active conditions.",
"parameters": {"type": "object", "required": ["patient_id"],
"properties": {"patient_id": {"type": "string"}}}}},
{"type": "function", "function": {
"name": "get_observations",
"description": "Get a patient's most recent observations for one LOINC code, newest first.",
"parameters": {"type": "object", "required": ["patient_id", "loinc_code"],
"properties": {"patient_id": {"type": "string"},
"loinc_code": {"type": "string", "description": "LOINC code, e.g. 2160-0"}}}}},
{"type": "function", "function": {
"name": "egfr_ckd_epi_2021",
"description": "Calculate eGFR (CKD-EPI 2021, race-free) and the KDIGO G stage. Use this instead of doing the math yourself.",
"parameters": {"type": "object", "required": ["creatinine_mg_dl", "sex", "birth_date", "on_date"],
"properties": {"creatinine_mg_dl": {"type": "number"},
"sex": {"type": "string", "description": "male or female"},
"birth_date": {"type": "string", "description": "YYYY-MM-DD"},
"on_date": {"type": "string", "description": "Date of the creatinine result, YYYY-MM-DD"}}}}},
]
def chat(messages):
body = json.dumps({"model": MODEL, "messages": messages, "tools": SCHEMAS, "stream": False,
"options": {"temperature": 1.0, "top_p": 0.95, "top_k": 64}}).encode()
req = urllib.request.Request(OLLAMA, data=body, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=600) as r:
return json.load(r)["message"]
messages = [
{"role": "system", "content": "You are a clinical assistant for a test system with synthetic data. "
"Use the tools to read the patient record before you answer."},
{"role": "user", "content": QUESTION},
]
for turn in range(8):
msg = chat(messages)
messages.append(msg)
calls = msg.get("tool_calls") or []
if not calls:
print(f"\n=== {MODEL} answer ===\n{msg['content']}")
break
for call in calls:
fn, args = call["function"]["name"], call["function"]["arguments"]
result = TOOLS[fn](**args)
print(f"[tool call] {fn}({json.dumps(args)})")
print(f"[result] {json.dumps(result)[:300]}")
messages.append({"role": "tool", "tool_name": fn, "content": json.dumps(result)})
Run it against the 26B. If you only pulled the E4B, leave the argument off and the script uses the default model. If your patient list has no Tremblay, pass your own question as a second argument, for example python3 fhir_agent.py medgemma2:e4b "Find the patient named Grimes and get their most recent serum creatinine." with a name from your list.
cd ~
python3 fhir_agent.py medgemma2:26b
MedGemma 2 decided on its own to search for the patient, pull the creatinine results, hand the newest value and the birth date to the calculator, and read the condition list. On the RTX 4090 the whole loop took 19.6 seconds:
[tool call] search_patients({"name": "Tremblay"})
[result] [{"id": "23537", "name": "Paul232 Francisco472 Tremblay80", "gender": "male", "birthDate": "1978-04-17"}]
[tool call] get_observations({"loinc_code": "2160-0", "patient_id": "23537"})
[result] [{"date": "2026-11-30T09:49:53+00:00", "value": 2.2549, "unit": "mg/dL"}, {"date": "2025-12-01T09:49:53+00:00", "value": 2.3101, "unit": "mg/dL"}, {"date": "2025-09-15T09:49:53+00:00", "value": 2.3595, "unit": "mg/dL"}]
[tool call] egfr_ckd_epi_2021({"birth_date": "1978-04-17", "creatinine_mg_dl": 2.2549, "on_date": "2026-11-30", "sex": "male"})
[result] {"age": 48, "egfr": 35.0, "unit": "mL/min/1.73m2", "stage": "G3b"}
[tool call] get_conditions({"patient_id": "23537"})
[result] ["Anemia (disorder)", "Asthma (disorder)", "Awaiting transplantation of kidney (situation)", "Chronic kidney disease stage 1 (disorder)", "Chronic kidney disease stage 2 (disorder)", "Chronic kidney disease stage 3 (disorder)", "Chronic kidney disease stage 4 (disorder)", "Disorder of kidney due to
=== medgemma2:26b answer ===
The patient, Paul Tremblay (ID: 23537), has a most recent serum creatinine of **2.2549 mg/dL** recorded on 2026-11-30.
Using the CKD-EPI 2021 equation, his **eGFR is 35.0 mL/min/1.73m²**, which corresponds to **CKD Stage G3b**.
The active conditions related to his kidney function include:
* Chronic kidney disease stage 4 (disorder)
* Awaiting transplantation of kidney (situation)
* Disorder of kidney due to diabetes mellitus (disorder)
* Essential hypertension (disorder)
* Microalbuminuria due to type 2 diabetes mellitus (disorder)
* Proteinuria due to type 2 diabetes mellitus (disorder)
* Prediabetes (finding)
* Other previous CKD stages (1, 2, 3) listed in the records.
Did the model get it right? The number is right, and the list needs a human. Synthea left CKD stages 1 to 4 all marked active, so the record contradicts itself, and the 26B leads with “stage 4” even though the value it just received says G3b. A clinician would catch that in seconds, which is why the model card insists every output is verified before anyone acts on it.
The calculator tool was not in our first version of the script. Without it, both models made the same correct tool calls and then did the CKD-EPI arithmetic in their heads. The 26B wrote the equation out and still landed on 31.65 instead of 35.0, and the E4B used an age of 46 and reported 12.47, which it called stage 5 kidney failure. A Python function costs ten lines and turns the number into something you can test, which is the same pattern Google describes when it says the model writes code for clinical calculations instead of computing them. Any score you care about (CHA2DS2-VASc, MELD, a dosing formula) belongs in a tool, not in what the model samples.
On the CPU-only Ubuntu 26.04 VM the same script runs fully local with no arguments, which means the E4B. It reached the same 35.0 and G3b, and the full loop took 3 minutes 21 seconds on 8 vCPUs.

Three minutes is too slow for a clinician waiting at a screen, but fine for a batch job that pre-computes kidney flags overnight, and nothing in that run left the VM. On a 24 GB GPU the same loop takes about 20 seconds, so the hardware decides which of those two jobs you can offer.
To give MedGemma 2 the same FHIR tools through a reusable, read-only MCP server instead of a one-off script, see our guide to building a FHIR MCP server for MedGemma 2.
Step 8: Add Open WebUI (optional)
Open WebUI gives non-technical users a chat window on top of the same Ollama service. Its container listens on 8080 by default, which HAPI FHIR already holds, so we move it to 3000 with the PORT variable and use host networking so it reaches Ollama on 127.0.0.1. Host networking also means Open WebUI binds to every interface by default, and the first account that signs up becomes the admin, so HOST=127.0.0.1 is not optional on a server with a public IP:
sudo docker run -d --name open-webui --restart unless-stopped --network host -e HOST=127.0.0.1 -e PORT=3000 -e OLLAMA_BASE_URL=http://127.0.0.1:11434 -v open-webui:/app/backend/data ghcr.io/open-webui/open-webui:main
Give it a minute to start, then confirm all three services listen on the loopback address only:
ss -ltn | grep -E ":(3000|8080|11434) "
The local address on every line should be 127.0.0.1. A 0.0.0.0:3000 line means the HOST variable did not reach the container:
LISTEN 0 4096 127.0.0.1:8080 0.0.0.0:*
LISTEN 0 2048 127.0.0.1:3000 0.0.0.0:*
LISTEN 0 4096 127.0.0.1:11434 0.0.0.0:*
Browse to http://localhost:3000 (or an SSH tunnel to it from your laptop), create the first account, which becomes the admin, and pick medgemma2:e4b or medgemma2:26b from the model menu. On the CPU-only VM the E4B thought for five minutes before giving a correct three-sentence answer:

Open WebUI also sends background requests to generate chat titles and tags, and on CPU those queue behind your answer, so a GPU makes a much bigger difference here than in a script. The Open WebUI with Docker Compose guide covers persistent settings, users and a reverse proxy if you keep it.
Can MedGemma 2 run without a GPU?
Yes, MedGemma 2 runs on CPU only, and both sizes run at about the same speed there because, again, active parameters set the pace. What you need is RAM for the weights and patience for the thinking tokens. We measured two machines:
- 32 threads of an AMD EPYC 7B12: 20.3 tokens/s for both E4B and 26B
- 8 vCPU Intel Xeon VM at 2.8 GHz with AVX-512: 7.5 tokens/s for E4B, 7.1 for 26B
- RAM taken: 6.1 GB for E4B, 18 GB for 26B
On the EPYC host we kept the RTX 4090 installed and forced CPU per request by setting the num_gpu option to 0, plus num_thread 32 to match the cores we had. You can compare GPU and CPU on your own hardware the same way, without touching drivers. This is the same request on the 8 vCPU VM:
curl -s http://localhost:11434/api/generate -d "{\"model\": \"medgemma2:e4b\", \"prompt\": \"Name the CKD stage for an eGFR of 35.\", \"stream\": false, \"think\": false, \"options\": {\"num_gpu\": 0}}" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d[\"response\"][:200]); print(\"%.2f tokens/s\" % (d[\"eval_count\"] / d[\"eval_duration\"] * 1e9))"
You get the first 200 characters of the answer and the generation speed.
To determine the CKD (Chronic Kidney Disease) stage for an eGFR (estimated Glomerular Filtration Rate) of 35, we use the standard CKD staging system:
* **Stage 1:** eGFR ≥ 90 mL/min/1.73 m²
* **S
7.61 tokens/s
At 7 tokens per second a short answer is fine. A thinking model often writes 600 to 900 tokens before the reply, though, so a single question takes you one to two minutes on the 8 vCPU box. If CPU is all you have, turn thinking off for simple lookups (--think=false on the CLI, "think": false in the API), keep it on for multi-step tool work, and pick the E4B because it needs a third of the RAM for the same speed. On the 8 vCPU VM the runner sat at about 380% CPU, one thread per physical core, so a box with more real cores helps more than one with more hyperthreads.
MedGemma 2 licence and intended use
MedGemma 2 is open weights, but it is not Apache 2.0 like Gemma. It ships under the Health AI Developer Foundations terms of use, and Hugging Face gates the original weights behind them (approval is automatic). The Ollama tags carry the same terms, which you can read with ollama show medgemma2:e4b --license. Between the terms and the model card, these are the points that matter for a self-hosted setup:
- Model card: outputs are not meant to directly inform diagnosis or treatment
- Terms: no use that makes Google a medical device manufacturer, and none the Prohibited Use Policy bans
- Terms: sharing it or a fine-tune passes these terms and a Notice file on
- Terms: clinical use needs your own health regulatory authorization where it applies
The model card is blunt about it: MedGemma is a starting point for developers to validate and adapt, and every output is preliminary until someone qualified checks it. Our X-ray and eGFR runs show why. Running it locally solves the data residency problem, and it does nothing for the accuracy problem.
What broke in the lab
Most of the snags were small, but each one would cost you time:
- ollama run hung in a script. Without a terminal on stdin,
ollama run model "prompt"waited for more input forever. Add< /dev/nullin loops and cron jobs. - The model did the math wrong. Both sizes miscalculated eGFR until we gave them a calculator tool (Step 7).
- Context was 4K on CPU. The VRAM-based default; the systemd drop-in in Step 3 fixes it.
- Wikimedia returned 429 and 403. Generic and fake user agents are refused; use a descriptive one.
- HAPI lost data on restart. The default image is in-memory H2.
- Port 8080 clash. HAPI FHIR and Open WebUI both default to it; we moved Open WebUI to 3000.
Our first benchmark run also looked bad for no real reason. While the 26B was still downloading in the background, the E4B took 60 seconds to load and generated 32 tokens per second; the same prompt on an idle box ran at 163. Benchmark after the pulls finish, and throw away the first run after a model loads.
What I would change before real patient data
This lab proves the model, the tool loop and the hardware numbers. It is not a deployment, and these are the changes I would make before any real record touched it:
- Give HAPI FHIR a PostgreSQL database and a backup, not in-memory H2
- Put authentication in front of FHIR and Open WebUI, and keep Ollama on 127.0.0.1
- Make every tool read-only, and log each tool call with its arguments
- Move every score and formula into tested code, never model arithmetic
- Validate the quantized model on your own cases before trusting a single output
If you outgrow one Ollama process (many users, batching, the full bfloat16 weights Google benchmarked), a dedicated server such as vLLM in production is the next step. Our Ollama vs vLLM vs llama.cpp benchmark shows what that switch buys on the same GPU. For a single team that wants private answers from synthetic or properly governed data, the 26B on one 24 GB card is already a usable clinical research assistant, as long as a human checks everything it says.