Fetching Fhir Resources logo

Fetching Fhir Resources

CommunityPopular
maziyarpanahi
fetching-fhir-resources

Fetches and pages FHIR R4 resources (Patient, DocumentReference, DiagnosticReport, Observation, Condition) from a FHIR REST server, decodes base64 attachments, and extracts clinical narrative for OpenMed. Use before OpenMed processing when pulling charts from an EHR FHIR API (Epic, Cerner/Oracle, HAPI, or any US Core server) and you need the note text de-identified and analyzed, then results rejoined by patient. Hand narrative to openmed.deidentify and openmed.analyze_text; openmed.interop.fhir_operations implements a $de-identify operation over Bundles. Trigger keywords: FHIR, R4, US Core, DocumentReference, DiagnosticReport, Bundle, _revinclude, presentedForm, base64, EHR API.

Overview

Publishermaziyarpanahi
Repositoryopenmed
Skill namefetching-fhir-resources
Stars
5.3K
Forks
677
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by maziyarpanahi on GitHub. Read the source before you install it.

Installation

Install the Fetching Fhir Resources AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/maziyarpanahi/openmed.git /tmp/openmed
mkdir -p .claude/skills
cp -r /tmp/openmed/skills/fetching-fhir-resources .claude/skills/fetching-fhir-resources
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Fetching Fhir Resources in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Fetching Fhir Resources on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Fetching Fhir Resources is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Fetching FHIR R4 Resources for OpenMed

FHIR R4 is the modern EHR API: a RESTful, JSON-or-XML interface over resources like Patient, Encounter, Condition, Observation, DiagnosticReport, and DocumentReference. The unstructured clinical text you want for NLP lives in DocumentReference.content.attachment and DiagnosticReport.presentedForm — usually base64-encoded PDF, RTF, or plain text. This skill pulls those resources, pages through results, decodes the attachments, and hands the narrative to OpenMed.

When to use

  • You have FHIR R4 access to an EHR (Epic, Oracle Health/Cerner, HAPI, Medplum, Azure/Google/AWS HealthLake) and want note text for de-id and NER.
  • You need to page a large search result set safely (Bundle.link[next]).
  • You want to pull a patient's documents/reports and rejoin NLP output by patient and encounter.

FHIR REST in one minute

Search is GET [base]/[Type]?param=value. Results come back as a searchset Bundle; the next page is the URL in Bundle.link where relation == "next". Use _count to size pages, _revinclude to pull related resources in one round trip, and _since/_lastUpdated for incremental sync.

GET /Patient?identifier=http://hospital.org/mrn|12345
GET /DocumentReference?patient=Patient/abc&category=clinical-note&_count=50
GET /DiagnosticReport?patient=Patient/abc&_revinclude=Observation:related

Quick start

Page a search, decode attachments, hand narrative to OpenMed:

python
import base64
import requests
import openmed

BASE = "https://fhir.example.org/r4"
HEADERS = {"Accept": "application/fhir+json", "Authorization": "Bearer <token>"}

def iter_bundle(url, params=None):
    """Yield resources across all pages following Bundle.link[next]."""
    while url:
        bundle = requests.get(url, params=params, headers=HEADERS, timeout=30).json()
        for entry in bundle.get("entry", []):
            yield entry.get("resource", {})
        params = None  # next links are fully-qualified
        url = next(
            (l["url"] for l in bundle.get("link", []) if l.get("relation") == "next"),
            None,
        )

def attachment_text(att):
    """Decode a FHIR Attachment to text (handles base64 and inline text/plain)."""
    if att.get("data"):
        raw = base64.b64decode(att["data"])
        if att.get("contentType", "").startswith("text/"):
            return raw.decode("utf-8", "replace")
        return ""  # PDF/RTF: route to OpenMed multimodal/OCR intake instead
    return ""

# Pull a patient's clinical notes and analyze each.
for doc in iter_bundle(f"{BASE}/DocumentReference",
                       {"patient": "Patient/abc",
                        "category": "clinical-note", "_count": 50}):
    for content in doc.get("content", []):
        text = attachment_text(content.get("attachment", {}))
        if not text.strip():
            continue
        deid = openmed.deidentify(text, method="replace", policy="hipaa_safe_harbor")
        result = openmed.analyze_text(deid.text, output_format="dict")
        patient_ref = doc.get("subject", {}).get("reference")  # rejoin key

Workflow

  1. Authenticate. Most production FHIR endpoints use SMART-on-FHIR OAuth2 (client-credentials for backend services). Scope to the minimum (system/DocumentReference.read, system/DiagnosticReport.read).
  2. Search narrowly. Filter by patient, category, type (LOINC), date, and _count. Prefer server-side filtering over client-side.
  3. Page via Bundle.link[next] until exhausted. Never assume one page.
  4. Extract narrative: DocumentReference.content.attachment and DiagnosticReport.presentedForm. Decode base64; for PDF/RTF/scanned content, route bytes to OpenMed's document intake (multimodal/ocr) rather than decoding as UTF-8.
  5. De-identify → analyze each narrative with OpenMed.
  6. Rejoin results to subject.reference (patient) and context.encounter so downstream consumers can group by patient/encounter — storing hashed, not raw, identifiers.

Hand-off to / from OpenMed

  • To OpenMed (client-side): decoded narrative → openmed.deidentifyopenmed.analyze_text. Carry subject.reference as the rejoin key.

  • Server-side $de-identify: openmed.interop.fhir_operations implements the FHIR $de-identify operation logic over the OpenMed privacy pipeline:

    • de_identify_resource(resource, policy=..., method=...)
    • de_identify_bundle(bundle, policy=..., method=...)
    • de_identify(parameters) — accepts/returns a Parameters envelope and reports modified element paths as an OperationOutcome. It de-identifies free-text strings, identifier values, and text.div narrative while never altering codes, references, systems, or temporal values. Use this to de-identify a whole fetched Bundle before storage:
    python
    from openmed.interop.fhir_operations import de_identify_bundle
    safe_bundle = de_identify_bundle(bundle, policy="hipaa_safe_harbor",
                                     method="replace")
  • Onward: re-export structured findings with openmed.clinical.exporters.fhir (to_bundle, to_operation_outcome).

Edge cases & gotchas

  • Attachments are often base64. attachment.data is base64; large files use attachment.url (a separate Binary fetch) instead. Handle both.
  • Non-text content types. application/pdf, text/rtf, scanned TIFF — do not utf-8 decode these; send bytes to OpenMed multimodal/OCR intake.
  • Pagination loops. Some servers emit cyclic or stale next links; cap page count and dedupe by resource id.
  • _revinclude vs _include. _include pulls referenced resources; _revinclude pulls resources that reference yours. Mixing them changes Bundle entry search.mode (match vs include) — filter on it.
  • Versioning & profiles. Confirm the server is R4 (/metadata CapabilityStatement) and US Core-conformant; field cardinality differs across FHIR versions.
  • Throttling. Respect 429/Retry-After; batch with _count and back off.
  • PHI everywhere. A FHIR resource is PHI by definition — never log raw resources; de-identify before persistence or analytics.

Standards & references

Frequently asked questions

What does the Fetching Fhir Resources AI skill do?

Fetches and pages FHIR R4 resources (Patient, DocumentReference, DiagnosticReport, Observation, Condition) from a FHIR REST server, decodes base64 attachments, and extracts clinical narrative for OpenMed. Use before OpenMed processing when pulling charts from an EHR FHIR API (Epic, Cerner/Oracle, HAPI, or any US Core server) and you need the note text de-identified and analyzed, then results rejoined by patient. Hand narrative to openmed.deidentify and openmed.analyze_text; openmed.interop.fhir_operations implements a $de-identify operation over Bundles. Trigger keywords: FHIR, R4, US Core,...

Why use Fetching Fhir Resources on TypingMind?

Because you install it once and use it with any model. Fetching Fhir Resources is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Fetching Fhir Resources in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/maziyarpanahi/openmed/tree/master/skills/fetching-fhir-resources. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Fetching Fhir Resources?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Fetching Fhir Resources?

As many as you like. As long as a model supports skills, you can use Fetching Fhir Resources with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Fetching Fhir Resources AI skill free?

Yes. It is published on GitHub by maziyarpanahi under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇