This prompt is designed for healthcare integration engineers who need to generate HL7 FHIR resources in XML format from structured or semi-structured clinical data. The primary job-to-be-done is converting a payload of clinical facts—such as patient demographics, observations, or medication orders—into a valid FHIR XML document that can be ingested by a downstream FHIR server, EHR, or HIE gateway. The ideal user is a developer or integration specialist building a production data pipeline, not a clinician interacting with a chat interface. You should use this prompt when the target FHIR resource type is known in advance (e.g., Patient, Observation, MedicationRequest), the input data contains the required clinical fields, and the output must pass automated XML schema validation against a specific FHIR version (R4, R4B, or R5).
Prompt
FHIR XML Resource Generation Prompt Template

When to Use This Prompt
Define the production boundary for the FHIR XML generation prompt, including the ideal user, required inputs, and scenarios where it should not be used.
Do not use this prompt when the target resource type is unknown at generation time, when the output format must be FHIR JSON instead of XML, or when the input data is too sparse to populate required FHIR elements. This prompt is also unsuitable for generating non-FHIR XML documents such as CDA, CCDA, or custom schemas. Before invoking this prompt in a pipeline, ensure you have resolved the FHIR version, the resource type, and any required profile or extension URLs. The prompt template expects placeholders like [RESOURCE_TYPE], [FHIR_VERSION], and [PROFILE_URLS] to be populated by the application layer, not inferred by the model. In high-stakes clinical contexts, always pair this prompt with a post-generation validation step that checks conformance against the official FHIR structure definition and any implementation guide profiles before the XML reaches a production system.
After reviewing this section, confirm that your use case fits the production boundary described here. If you are generating FHIR JSON, handling unknown resource types, or working with non-FHIR XML formats, select a different prompt from the XML and Markup Document Structure playbook. If your use case matches, proceed to the prompt template section to copy the ready-to-adapt template and begin wiring it into your pipeline.
Use Case Fit
Where this prompt works and where it does not. FHIR XML generation requires strict schema adherence, clinical terminology mapping, and downstream validation. Use this prompt when you need structured healthcare data interchange, not when you need clinical reasoning or free-text narrative.
Good Fit: Validated FHIR Resource Generation
Use when: You need to generate a specific FHIR resource type (Patient, Observation, MedicationRequest) in XML format from structured or semi-structured input data. Guardrail: Provide the target FHIR profile URL and resource type in the prompt. Validate output against the FHIR structure definition before ingestion.
Bad Fit: Clinical Decision Support
Avoid when: The task requires clinical reasoning, diagnosis, treatment recommendations, or interpretation of medical data. Guardrail: This prompt generates XML structure, not clinical insight. Route clinical reasoning tasks to specialized models with appropriate regulatory clearances and always require licensed clinician review.
Required Inputs: Resource Type and Data Payload
What to watch: The model cannot invent valid FHIR XML without knowing the target resource type, required identifiers, and clinical data fields. Guardrail: Always include the FHIR resource type, mandatory identifier system values, and a structured data payload. For extensions, provide the extension URL and value explicitly.
Operational Risk: Terminology Binding Failures
What to watch: FHIR resources often require coded values from terminologies like SNOMED CT, LOINC, or RxNorm. The model may generate plausible but incorrect codes. Guardrail: Provide allowed value sets or code system URLs in the prompt. Post-validate all coded elements against a terminology server before accepting the output.
Operational Risk: Narrative Text Drift
What to watch: The text.div narrative section may contain hallucinated clinical details that contradict the structured data. Guardrail: Either omit narrative generation and generate it separately from structured data, or validate that the narrative faithfully represents the coded resource content without adding unsupported claims.
Operational Risk: Reference Integrity
What to watch: FHIR references to other resources (Patient, Practitioner, Encounter) may point to non-existent or incorrect logical IDs. Guardrail: Provide a reference map of valid logical IDs in the prompt context. Validate all reference targets exist in the target system before committing the resource.
Copy-Ready Prompt Template
A copy-ready prompt template for generating valid FHIR XML resources from clinical data, with placeholders for version, resource type, and constraints.
This section provides the core prompt template for generating HL7 FHIR resources in XML format. The template is designed to be copied directly into your AI harness, with square-bracket placeholders that you replace with concrete values before execution. It instructs the model to produce only the XML document, with no surrounding explanation or markdown fences, ensuring the output can be piped directly into a validation step or downstream system.
textGenerate a valid HL7 FHIR [FHIR_VERSION] [RESOURCE_TYPE] resource in XML format from the following clinical data: [INPUT_DATA] Constraints: - The output must validate against the [RESOURCE_TYPE] structure definition and the following profiles: [PROFILES]. - Include the required FHIR namespace declaration on the root element. - Use the narrative text element to include a human-readable summary of the resource. - If the input contains references to other resources, use contained resources where appropriate, otherwise use logical references. - [ADDITIONAL_CONSTRAINTS] Return only the XML document with no surrounding explanation or markdown fences.
Adapt this template by replacing each placeholder with concrete values for your integration. [FHIR_VERSION] should be a release like R4 or R5. [RESOURCE_TYPE] is the target resource, such as Patient, Observation, or MedicationRequest. [INPUT_DATA] is the clinical data payload—this can be a JSON object, a narrative description, or a structured record from an EHR system. [PROFILES] should list any conformance profiles (e.g., http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient) that the output must satisfy. Use [ADDITIONAL_CONSTRAINTS] to inject domain-specific rules, such as required extensions, identifier systems, or terminology bindings.
Before deploying this prompt into a production pipeline, wire the output into an XML schema validator and a FHIR validator (such as the HL7 FHIR Validator or a profile-specific implementation guide checker). If the validator rejects the output, use a repair prompt from the Output Repair and Validation Prompts pillar to correct structural errors. For high-stakes clinical workflows, always require human review of generated resources before they are persisted to a FHIR server or exchanged with downstream systems.
Prompt Variables
Required inputs for the FHIR XML Resource Generation prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before generation begins.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[FHIR_RESOURCE_TYPE] | The FHIR resource type to generate (e.g., Patient, Observation, MedicationRequest) | Patient | Must match a valid FHIR R4 resource type name from the FHIR specification. Case-sensitive. Validate against the official resource list before prompt assembly. |
[CLINICAL_CONTEXT] | Unstructured clinical notes, discharge summary, or encounter text to extract data from | Patient presents with chest pain. History of hypertension. Current medications: Lisinopril 10mg daily. | Free-text input. Must be non-empty. If the source contains PHI, ensure it is authorized for processing. Null not allowed. |
[FHIR_VERSION] | The FHIR specification version to target | R4 | Must be one of: R4, R4B, R5. Default to R4 if not specified. Validate against the supported version list in the generation harness. |
[PROFILE_URLS] | Optional list of FHIR profile canonical URLs the resource must conform to | Each URL must be a valid absolute URI. If empty array, no profile constraints are applied. Null allowed; defaults to empty array. | |
[EXTENSION_DEFINITIONS] | Optional custom extension definitions with URL and value mappings | [{"url": "http://example.org/fhir/StructureDefinition/preferred-pharmacy", "valueString": "Central Pharmacy"}] | Each object must contain a url key with a valid URI and a value key matching the extension's value type. Null allowed. |
[CONTAINED_RESOURCES] | Optional array of resource objects to embed as contained resources | [{"resourceType": "Practitioner", "id": "p1", "name": [{"family": "Smith"}]}] | Each object must include resourceType and id fields. The id must be referenced by the parent resource. Null allowed. |
[NARRATIVE_GENERATION] | Flag indicating whether to generate a human-readable text narrative in the resource | Must be boolean true or false. When true, the model must produce a valid XHTML narrative div. When false, the text element is omitted. | |
[OUTPUT_ENCODING] | XML document encoding declaration to use | UTF-8 | Must be a valid IANA character set name. Default to UTF-8. Validate against the XML serializer's supported encodings before generation. |
Implementation Harness Notes
How to wire the FHIR XML generation prompt into a reliable application pipeline with validation, retries, and human review.
Integrating the FHIR XML Resource Generation Prompt into a production system requires more than a single API call. The prompt is designed to be one step in a structured generation pipeline that includes input sanitization, schema validation, retry logic, and human-in-the-loop review for high-risk resources. The harness must treat the LLM as an unreliable component that occasionally produces malformed XML, invents codes, or misplaces required elements—and must catch these failures before the output reaches a downstream EHR, FHIR server, or clinical data repository.
Begin by constructing the prompt request with strict tool-use or structured output mode if your model provider supports it. For OpenAI, use response_format with a JSON Schema that wraps the XML string to prevent markdown wrapping; for Anthropic, use the XML-generation system prompt with explicit stop sequences after the closing root element. Validate the raw output immediately: parse the XML string with a strict parser (e.g., lxml with schema validation enabled), check for well-formedness, and then validate against the target FHIR structure definition using a library like fhir.resources (Python) or the HL7 FHIR Validator. If validation fails, classify the error: schema violations (missing required elements, wrong types) should trigger a retry with the error message injected into the [CONSTRAINTS] placeholder; code system errors (invented or mismatched terminology) should trigger a terminology lookup step that replaces invalid codes with valid ones from a terminology server before retrying; contained resource errors should trigger a decomposition step that generates contained resources separately and reassembles them.
Implement a retry budget of 2–3 attempts with escalating interventions. On the first failure, append the validator error to the prompt and retry. On the second failure, switch to a more capable model or add explicit few-shot examples of the failing element. If all retries fail, escalate to a human review queue with the original input, the failed outputs, and the validator error log. For high-risk resources like MedicationRequest, AllergyIntolerance, or Procedure, require human approval even on successful validation by routing the output to a review interface that displays the generated XML alongside the source clinical context. Log every generation attempt with the prompt version, model, input hash, output, validation result, and reviewer decision for audit trails and prompt regression testing. Never allow unvalidated FHIR XML to flow into a production FHIR server or clinical workflow.
Expected Output Contract
Field-level contract for the generated FHIR XML resource. Use this table to build a post-generation validator that confirms structural correctness before the output reaches a downstream FHIR server.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
Root element (e.g., <Patient>, <Observation>) | FHIR resource XML element | Must match one of the valid FHIR resource type names. Validate against the FHIR R4/R5 resource list. | |
xmlns attribute on root | URI string | Must equal 'http://hl7.org/fhir'. Reject if missing or if the namespace URI is incorrect. | |
<id> element | FHIR id primitive | If present, must match regex [A-Za-z0-9-.]{1,64}. Assign a UUID if absent and required by the downstream system. | |
<meta> element | Complex FHIR type | If present, must contain at least one valid child (e.g., <versionId>, <lastUpdated>, <profile>). Reject empty <meta/>. | |
<identifier> array | Array of FHIR Identifier | Each element must have a <system> and <value>. <system> must be a valid URI. Reject if <value> is empty. | |
<code> element (where applicable) | FHIR CodeableConcept | If present, must contain at least one <coding> element. Each <coding> must have a <system> (URI) and <code> (string). | |
<extension> elements | Array of FHIR Extension | Each extension must have a 'url' attribute (URI). Reject extensions with a 'url' that is not an absolute URI. | |
<contained> resources | Array of FHIR resources | Each contained resource must have a local reference id (e.g., #ref). Validate that all internal references resolve within the document. |
Common Failure Modes
FHIR XML generation is brittle. These are the most common failures when prompting an LLM to produce valid FHIR resources, along with concrete mitigations you can add to your prompt harness.
Invalid Resource Type or Missing Required Fields
What to watch: The model generates a plausible-looking XML document but uses an incorrect FHIR resource type (e.g., Condition instead of Observation) or omits mandatory fields like status or code. FHIR validators will reject these outright. Guardrail: Provide the exact resource type and a minimal valid example in the prompt. Add a post-generation validation step that checks for required fields per the FHIR structure definition before the output leaves the pipeline.
Incorrect or Missing Namespace Declarations
What to watch: The model omits the xmlns="http://hl7.org/fhir" declaration on the root element or fails to declare extension namespaces. Parsers will treat elements as unqualified, breaking downstream ingestion. Guardrail: Explicitly require the FHIR namespace in the prompt's output schema. Use a schema-aware XML validator that checks namespace URIs, not just element names, before accepting the output.
Malformed Extension Structures
What to watch: Extensions are nested incorrectly—url and value[x] placed as attributes instead of child elements, or the extension wrapper omitted entirely. This is the most common structural error in generated FHIR XML. Guardrail: Include a canonical extension example in the few-shot prompt. Validate extension structure against the FHIR Extension definition using an automated schema check that verifies the url/value[x] child pattern.
Coding and CodeableConcept Type Confusion
What to watch: The model flattens a CodeableConcept into a single code element or nests coding incorrectly. It may also invent system URIs or codes that don't exist in the target value set. Guardrail: Provide the exact system and code values when known, or constrain the model to a specific value set binding. Add a terminology validation step that checks codes against the declared system URI.
Reference Integrity and Contained Resource Errors
What to watch: Internal references (e.g., #ref1) don't match any id in contained resources, or the model references external resources with malformed URLs. This breaks FHIR's graph resolution. Guardrail: If using contained resources, require the model to list all contained ids first, then reference them. Add a post-check that resolves every reference value starting with # to a contained resource id.
Date and DateTime Format Violations
What to watch: The model uses ISO 8601 formats that FHIR doesn't accept (e.g., timezone offsets without minutes, or dates missing required precision for the field). FHIR date validation is stricter than general ISO 8601. Guardrail: Specify the exact FHIR date format in the prompt (e.g., YYYY-MM-DD for date, YYYY-MM-DDThh:mm:ss+zz:zz for instant). Run a regex-based date format validator on all date-valued elements before downstream processing.
Evaluation Rubric
Use this rubric to test the quality of generated FHIR XML before integrating it into a healthcare application. Each criterion targets a specific failure mode common in LLM-generated XML for regulated environments.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
XML Well-Formedness | Document parses without errors in a standard XML parser (e.g., lxml, Xerces). | Parser throws fatal error: mismatched tags, unclosed elements, or invalid character references. | Automated: Parse with lxml.etree.fromstring(). Fail on any XMLSyntaxError. |
FHIR Schema Validation | Document validates against the target FHIR R4/R5 base schema and any referenced profiles. | Schema validator returns errors for missing required elements, incorrect data types, or cardinality violations. | Automated: Validate against official FHIR XSD or use the FHIR Validator JAR with the -xml flag. |
Resource Type Correctness | The root element's <resourceType> value matches the requested resource (e.g., Patient, Observation). | Root element is a different resource type or the <resourceType> element is missing. | Automated: XPath check for /[ResourceType]/resourceType/value/@value == [REQUESTED_RESOURCE]. |
Narrative Text Presence | A human-readable <text> block with a <div> is present and contains a non-empty summary of the resource. | The <text> element is missing, empty, or contains only whitespace. Status is 'empty' or 'extensions'. | Automated: XPath check for string-length(//text/div) > 50. Manual: Review for clinical coherence. |
Identifier and Coding System Validity | All <system> URIs in Codings and Identifiers are valid, non-404 FHIR terminology URLs (e.g., http://loinc.org). | A <system> value is a placeholder like 'http://example.org', a broken URL, or a non-FHIR system. | Automated: Regex match against a whitelist of known FHIR system URIs. Manual: Spot-check for hallucinated systems. |
Extension URL Validity | All <extension url='...'> values reference a known FHIR extension or a valid project-specific URL defined in [PROFILE_URLS]. | Extension url is a hallucinated or generic placeholder (e.g., 'http://example.org/fhir/StructureDefinition/age'). | Automated: Cross-reference extension URLs against a provided allowlist. Fail on unknown URLs not in [PROFILE_URLS]. |
Contained Resource Integrity | Any <contained> resources are internally consistent, have a local #id, and are correctly referenced by a '#' prefix in the parent. | A reference to a contained resource uses a full URL or an unresolvable fragment ID. The contained resource is missing required fields. | Automated: Resolve all '#' references within the document. Verify that each referenced ID exists in a <contained> block. |
Date and DateTime Formatting | All date-relevant fields (e.g., birthDate, effectiveDateTime) use ISO 8601 format with the correct FHIR precision (YYYY, YYYY-MM, YYYY-MM-DDThh:mm:ss+zz:zz). | A date is formatted as 'January 1, 2020', uses a 2-digit year, or is missing the required timezone offset. | Automated: Regex validation against FHIR date/dateTime regex patterns. Fail on any non-matching string. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt\nUse the base prompt with a single FHIR resource type and minimal profile constraints. Replace [FHIR_RESOURCE_TYPE] with a concrete type like `Patient` or `Observation`. Remove or comment out the [PROFILE_URL] constraint block. Accept manual spot-checking instead of automated schema validation.\n\n### Watch for\n- Missing required FHIR elements like `status` or `code`\n- Incorrect XML namespace declarations\n- Silent format drift when switching resource types\n- Overly broad instructions producing narrative-only resources without structured data

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us