Skip to content
Back to Blog
Healthcare AIArchitectureCodeDiagrams

HL7 v2 to FHIR with LLMs: Keep the Model Out of the Hot Path

An LLM should write your integration mappings, not translate your messages. How to use a model at design time, compile the result to deterministic transforms, and validate everything against US Core.

October 27, 20268 min read
HL7 v2FHIRUS CoreLLMIntegration
HL7 v2 to FHIR with LLMs: Keep the Model Out of the Hot Path

Every healthcare integration project meets the same pile of data: HL7 v2 feeds with site-specific codes, C-CDA documents that vary by vendor, and a surprising number of faxes. The destination is usually FHIR, and the mapping work between the two has always been slow and specialized.

LLMs are very good at this kind of reading. So the first idea is obvious: send each message to a model and ask for FHIR back. It makes a great demo. It is also the wrong architecture. The better split is to let the model write the mapping while a deterministic pipeline runs the messages.

Why Not Translate Every Message with a Model

A lab interface can send hundreds of thousands of messages a day, and each one becomes part of a patient record. Per-message translation runs into five problems:

  • Nondeterminism. The same message can produce two different resources. That is hard to defend for a clinical record.
  • Audit. When someone asks why a result changed on Tuesday, "the model decided" is not an answer. A versioned mapping is.
  • PHI exposure. Every request carries patient data across a boundary, which multiplies your risk surface.
  • Cost and latency. Both scale with message volume, and interfaces have peaks you do not control.
  • Silent failure. This one matters most, because a wrong result can pass every automated check.

Valid Is Not the Same as Correct

A FHIR validator checks that a code exists and fits the profile. It cannot tell that LOINC 2345-7 (glucose) was used where the lab meant fasting glucose, 1558-6. Both pass. A model that guesses plausibly produces exactly this kind of error.

Design Time and Run Time

The fix is to treat these as two separate systems.

Design timeRun time
JobCreate or update a mappingProcess live messages
InputDe-identified samplesIdentified messages
ModelAllowedNot allowed for structured feeds
OutputA versioned, reviewed artifactFHIR resources
PaceHours to days, with a person involvedMilliseconds, unattended

The approved mapping is the only thing that crosses from one side to the other. At run time, the transform is a pure function: same input, same output, every time. You can replay last month's traffic through it, diff two versions, and show an auditor exactly what ran.

Ask for a Mapping, Not a Message

Give the model a de-identified sample of a feed and ask for a typed proposal. The most important field in this schema is open_questions. Without it, the model has no way to express doubt except by guessing.

mapping/propose.py
from typing import Literal
 
import anthropic
from pydantic import BaseModel
 
 
class FieldMapping(BaseModel):
    source: str  # e.g. "OBX-5"
    target: str  # e.g. "Observation.valueQuantity"
    transform: Literal["copy", "code_lookup", "ucum_unit", "site_datetime", "value_map"]
    confidence: float
    rationale: str
 
 
class CodeCandidate(BaseModel):
    local_code: str
    loinc_candidates: list[str]
 
 
class OpenQuestion(BaseModel):
    field: str
    question: str
    why_it_matters: str
 
 
class MappingProposal(BaseModel):
    target_profile: str
    fields: list[FieldMapping]
    codes: list[CodeCandidate]
    open_questions: list[OpenQuestion]
 
 
SYSTEM_PROMPT = """You write mappings from HL7 v2 feeds to FHIR US Core profiles.
Propose a mapping for the whole feed. Do not translate individual messages.
A local code often means something the message does not state. When the samples
do not settle a meaning, add an open question instead of choosing the likely answer."""
 
client = anthropic.Anthropic()
 
 
class NeedsHumanMapping(Exception):
    """The model declined or returned nothing usable. Route to an analyst."""
 
 
def propose_mapping(deidentified_samples: list[str], profile: str) -> MappingProposal:
    samples = "\n\n".join(deidentified_samples)
    response = client.beta.messages.parse(
        model="claude-opus-5-5",
        max_tokens=16000,
        betas=["server-side-fallback-2026-07-01"],
        fallbacks="default",
        output_config={"effort": "high"},
        system=SYSTEM_PROMPT,
        messages=[{
            "role": "user",
            "content": f"Target profile: {profile}\n\nSamples:\n{samples}",
        }],
        output_format=MappingProposal,
    )
    if response.stop_reason == "refusal" or response.parsed_output is None:
        raise NeedsHumanMapping(response.stop_reason)
    return response.parsed_output

Here is the kind of line that makes open_questions earn its place:

Synthetic ORU^R01 segment
OBX|3|NM|EGFR^eGFR CKD-EPI^L||52|mL/min/1.73m2|>=60|L|||F

A good answer maps EGFR to LOINC 98979-8, the CKD-EPI 2021 equation, and then asks a question: the message does not state the equation year, and older equations use different codes. Only the lab can answer that. The mapping waits for a person, and it should.

Golden Replay Is the Real Test

Schema validation tells you a proposal is well formed. Replay tells you whether it works.

Build a golden set

Collect messages that cover each message type, odd segments, and known edge cases. Have an analyst review the expected FHIR for each one. Use synthetic or de-identified data so the fixtures can live in the repository.

Seed known ambiguity

Add fixtures where the correct behavior is to ask. If a proposal maps a seeded ambiguous code without raising a question, fail it. This is what tests for overconfidence.

Replay and classify

Run the candidate mapping over every fixture and sort the results into identical, changed, and invalid. Show changes as a diff for review.

Validate against the profile

Send each output through the HAPI FHIR validator using the FHIR $validate operation. Any error blocks the release.

mapping/replay.py
from dataclasses import dataclass, field
 
import httpx
 
 
@dataclass
class ReplayReport:
    identical: int = 0
    changed: list[str] = field(default_factory=list)
    invalid: list[str] = field(default_factory=list)
 
    @property
    def can_publish(self) -> bool:
        # Changes are allowed, but a person must review them. Invalid output is not allowed.
        return not self.invalid
 
 
def has_errors(resource: dict, profile: str, fhir_base: str) -> bool:
    response = httpx.post(
        f"{fhir_base}/{resource['resourceType']}/$validate",
        params={"profile": profile},
        json=resource,
        timeout=30,
    )
    issues = response.json().get("issue", [])
    return any(issue["severity"] in ("error", "fatal") for issue in issues)
 
 
def replay(transform, fixtures, profile: str, fhir_base: str) -> ReplayReport:
    report = ReplayReport()
    for fixture in fixtures:
        output = transform(fixture.message)
        if has_errors(output, profile, fhir_base):
            report.invalid.append(fixture.id)
        elif output == fixture.expected:
            report.identical += 1
        else:
            report.changed.append(fixture.id)
    return report

Terminology Is Where It Gets Hard

Structure is the easy part. Local codes are the hard part, because a site's GLU may mean random glucose on one interface and fasting glucose on another. A workable order of operations:

  1. Check a reviewed crosswalk first. Anything a person has already approved is resolved without a model.
  2. Search for candidates. Use the local name, units, and specimen to pull candidates from LOINC with a vector index such as pgvector, so the model chooses from real codes rather than recalling them.
  3. Let the model rank and explain. It returns its choice, its reasoning, and any question it has.
  4. Confirm the code exists. Check it against a terminology server. Never trust a code from memory.
  5. Save the decision. Approved answers go back into the crosswalk, so the model is needed less over time.

Units need the same care. FHIR quantities use UCUM, so mL/min/1.73m2 becomes mL/min/{1.73_m2} and mcg/ml becomes ug/mL.

Details That Break Naive Mappings

DetailWhy it hurtsWhat to do
Timestamps with no offsetFHIR requires an offset whenever a time is presentMake the site's IANA timezone part of feed config, and test across daylight-saving changes
Corrected results (OBX-11 = C)A new resource leaves the old wrong value activeMatch on a stable identifier and update the original
Reused local codesThe same code can mean different tests across sitesScope every crosswalk entry to its sending system
Text results (FT, TX)Long values may span several OBX segmentsReassemble them before mapping
Unknown segmentsVendors add Z segments freelyKeep the raw message so you can reprocess later

Do Not Start from Zero

HL7 publishes a V2-to-FHIR Implementation Guide with concept maps for common segments. Give it to the model as context and treat it as the baseline, so the model's work is focused on what is specific to your site.

Where a Model Still Belongs at Run Time

Some inputs have no structure to compile against. Faxed referrals are the classic case: there is no stable format, so a vision model has to read them. That is a reasonable exception as long as the exception is explicit. Keep these messages on a separate path, require human review for every result, and report the share of traffic that takes this path so it cannot quietly grow.

The same principle applies when validation fails in production. Do not let a model repair the live message. Quarantine it with the reason, open a mapping task, and let the fix arrive as a new reviewed version.

Use the model where a person can check its work

Models are excellent at reading messy interfaces and proposing how to map them. Keep that work at design time, ask for questions as well as answers, test against golden fixtures, and publish a deterministic artifact. You get most of the speed with none of the runtime uncertainty.

References

TC

TwilightCore Team

AI & Digital Studio

We build production AI systems and full-stack applications. Writing about the technical decisions, architecture patterns, and engineering practices behind real-world projects.