Skip to content

API reference

Generated from docstrings. Everything listed is importable from the top-level fhirground namespace unless noted.

Pipeline

fhirground.pipeline

The pipeline: note in, validated FHIR Bundle out.

Stage order is SPEC §4.2, and it is the order that makes the guarantees hold:

chunk → extract → ground → assert → normalize → resolve → dedup
      → map → validate → score → bundle

Grounding comes before the assertion policy so an ungrounded mention is dropped before anything decides what it means. Terminology resolution comes before deduplication so that two surface forms of one concept merge on their shared code. Validation comes before confidence so a resource that fails a project rule is dropped rather than scored.

Every dropped mention is counted with a reason, and every emitted resource carries its evidence. A note that produces nothing produces a reason for it.

Pipeline

Wires preprocessing, extraction, mapping, validation, and scoring.

Example::

pipe = Pipeline(PipelineConfig(), backend=MockBackend(), resolvers=resolvers)
result = pipe.run_note(note)
print(result.bundle)
Source code in src/fhirground/pipeline.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
class Pipeline:
    """Wires preprocessing, extraction, mapping, validation, and scoring.

    Example::

        pipe = Pipeline(PipelineConfig(), backend=MockBackend(), resolvers=resolvers)
        result = pipe.run_note(note)
        print(result.bundle)
    """

    def __init__(
        self,
        config: PipelineConfig | None = None,
        *,
        backend: Backend,
        resolvers: ResolverConfig | None = None,
        calibrator: Calibrator | None = None,
    ) -> None:
        self.config = config or PipelineConfig()
        self.config.validate_consistency()
        self.backend = backend
        self.resolvers = resolvers or ResolverConfig()
        self.calibrator = calibrator
        self.schema = build_mention_schema()
        self.schema_digest = schema_digest(self.schema)
        self.cache = CallCache(self.config.cache_path) if self.config.cache_path else None

    # -- one note -------------------------------------------------------

    def run_note(self, note: NoteInput) -> NoteResult:
        """Run the full pipeline on one note."""
        cfg = self.config
        urls = cfg.extension_urls
        result = NoteResult(note=note)

        plan = chunk_note(
            note.text,
            note.note_id,
            max_chars=cfg.max_chars,
            overlap_chars=cfg.overlap_chars,
            section_headers=cfg.section_headers,
            respect_sections=cfg.respect_sections,
        )

        # --- extract ---------------------------------------------------
        raw_items: list[tuple[Mention, Resolution, Grounding, str, int]] = []
        sample_sets: list[list[tuple[Mention, Resolution]]] = []
        total_repairs = 0
        tokens_in = tokens_out = 0
        latency = 0.0
        n_mentions = 0

        for chunk in plan.chunks:
            extraction = extract_chunk(
                chunk,
                self.backend,
                self.schema,
                note_datetime=note.note_datetime.isoformat(),
                temperature=cfg.temperature,
                samples=cfg.samples,
                max_repairs=cfg.max_repairs,
                cache=self.cache,
                schema_digest=self.schema_digest,
            )
            total_repairs += extraction.repairs
            tokens_in += extraction.tokens_in
            tokens_out += extraction.tokens_out
            latency += extraction.latency_s

            if not extraction.ok:
                result.errors.append(
                    f"chunk {chunk.chunk_id} failed after {extraction.repairs} repair(s): "
                    f"{extraction.error}"
                )
                continue

            # Extra samples are kept only to measure consistency.
            for sample in extraction.samples[1:]:
                sample_sets.append(
                    [(m, self.resolvers.resolve(m.text, m.mention_type)) for m in sample.mentions]
                )

            for mention in extraction.mentions.mentions:
                n_mentions += 1
                grounding = ground_mention(
                    mention.evidence,
                    plan.chunks,
                    note.text,
                    preferred_chunk_id=chunk.chunk_id,
                    fuzzy_threshold=cfg.fuzzy_threshold,
                )
                if grounding is None:
                    result.dropped.append((mention, DropReason.UNGROUNDED))
                    result.debug.append(
                        MentionTrace(
                            mention=mention,
                            chunk_id=chunk.chunk_id,
                            drop_reason=DropReason.UNGROUNDED,
                        )
                    )
                    continue
                resolution = self.resolvers.resolve(mention.text, mention.mention_type)
                raw_items.append(
                    (mention, resolution, grounding, chunk.chunk_id, extraction.repairs)
                )

        # --- dedup -----------------------------------------------------
        groups = dedup_mentions([(m, r, g) for m, r, g, _c, _rep in raw_items])
        repairs_by_key = {
            (m.mention_type.value, m.normalized_text, m.assertion.value): rep
            for m, _r, _g, _c, rep in raw_items
        }
        chunk_by_key = {
            (m.mention_type.value, m.normalized_text, m.assertion.value): c
            for m, _r, _g, c, _rep in raw_items
        }

        # --- policy, map, validate, score ------------------------------
        emitted: list[dict[str, Any]] = []
        for index, group in enumerate(groups):
            mention = group.mention
            identity = (
                mention.mention_type.value,
                mention.normalized_text,
                mention.assertion.value,
            )
            chunk_id = chunk_by_key.get(identity, "")
            repairs = repairs_by_key.get(identity, 0)
            best = group.best_grounding
            section = section_at(plan.sections, best.start)

            decision = decide(
                mention,
                emit_refuted=cfg.emit_refuted,
                section=section,
                respect_non_patient_sections=cfg.respect_non_patient_sections,
            )
            trace = MentionTrace(
                mention=mention,
                chunk_id=chunk_id,
                grounding=best,
                resolution=group.resolution,
                decision=decision,
                n_duplicates=group.n_duplicates,
            )

            if not decision.emit:
                reason = decision.reason or DropReason.UNSUPPORTED
                result.dropped.append((mention, reason))
                trace.drop_reason = reason
                result.debug.append(trace)
                continue

            components = self._components(group, repairs, sample_sets, n_samples=cfg.samples)
            score = aggregate(components, cfg.weights)
            calibrated = False
            if self.calibrator is not None and self.calibrator.fitted:
                score = self.calibrator.transform(score)
                calibrated = True

            trace.components = components
            trace.score = score
            trace.calibrated = calibrated

            if score < cfg.min_confidence:
                result.dropped.append((mention, DropReason.BELOW_THRESHOLD))
                trace.drop_reason = DropReason.BELOW_THRESHOLD
                result.debug.append(trace)
                continue

            resource = self._map(group, decision, note, score, calibrated, index, urls)
            if resource is None:
                result.dropped.append((mention, DropReason.UNSUPPORTED))
                trace.drop_reason = DropReason.UNSUPPORTED
                result.debug.append(trace)
                continue

            report = validate_resource(
                resource,
                note.text,
                urls=urls,
                require_quote_match=cfg.include_quotes,
            )
            trace.validation = report
            if not report.ok:
                result.dropped.append((mention, DropReason.VALIDATION_FAILED))
                trace.drop_reason = DropReason.VALIDATION_FAILED
                result.validation.extend(report)
                result.debug.append(trace)
                continue

            result.validation.extend(report)
            trace.resource_id = resource["id"]
            trace.resource_type = resource["resourceType"]
            emitted.append(resource)
            result.debug.append(trace)

        # --- provenance and bundle -------------------------------------
        if emitted:
            from fhirground import __version__
            from fhirground.validate import parse_with_models

            provenance = build_provenance(
                resource_id=f"prov-{note.note_id}",
                target_references=[f"{r['resourceType']}/{r['id']}" for r in emitted],
                source_reference=note.source_reference,
                patient_ref=note.patient_ref,
                model_id=getattr(self.backend, "model_id", "unknown"),
                prompt_version=PROMPT_VERSION,
                package_version=__version__,
                fhir_library=_fhir_library(),
                schema_digest=self.schema_digest,
                backend_name=getattr(self.backend, "name", "unknown"),
            )
            prov_report = parse_with_models(provenance)
            result.validation.extend(prov_report)
            if prov_report.ok:
                emitted.append(provenance)

        result.resources = emitted
        result.bundle = build_bundle(emitted, bundle_id=f"bundle-{note.note_id}")
        result.validation.extend(
            __import__("fhirground.validate", fromlist=["parse_with_models"]).parse_with_models(
                result.bundle
            )
        )

        result.stats = {
            "n_chunks": len(plan.chunks),
            "chunk_coverage": round(plan.coverage(len(note.text)), 6),
            "n_mentions": n_mentions,
            "n_groups": len(groups),
            "n_resources": len([r for r in emitted if r["resourceType"] != "Provenance"]),
            "n_dropped": len(result.dropped),
            "repairs": total_repairs,
            "tokens_in": tokens_in,
            "tokens_out": tokens_out,
            "latency_s": round(latency, 4),
            "drop_counts": result.drop_counts(),
            "resource_counts": result.resource_counts(),
        }
        return result

    # -- many notes -----------------------------------------------------

    def run(self, notes: Iterable[NoteInput], concurrency: int = 4) -> Iterator[NoteResult]:
        """Run over many notes.

        Args:
            notes: The notes.
            concurrency: Worker threads. The work is IO-bound on a backend
                call, so threads are the right tool. ``1`` runs inline, which
                keeps tracebacks readable while debugging.

        Yields:
            One :class:`NoteResult` per note, in input order.
        """
        note_list = list(notes)
        if concurrency <= 1:
            for note in note_list:
                yield self.run_note(note)
            return

        from concurrent.futures import ThreadPoolExecutor

        with ThreadPoolExecutor(max_workers=concurrency) as pool:
            yield from pool.map(self.run_note, note_list)

    # -- internals ------------------------------------------------------

    def _components(
        self,
        group: MentionGroup,
        repairs: int,
        sample_sets: list[list[tuple[Mention, Resolution]]],
        *,
        n_samples: int,
    ) -> ConfidenceComponents:
        """Assemble the confidence components for one group."""
        consistency = None
        if n_samples > 1 and sample_sets:
            matches = matches_for_consistency((group.mention, group.resolution), sample_sets)
            consistency = self_consistency(matches, len(sample_sets))

        terminology = group.resolution.score if group.resolution.is_coded else None
        return ConfidenceComponents(
            g=group.best_grounding.score,
            c=consistency,
            t=terminology,
            v=validation_component(repairs),
            l=None,
        )

    def _map(
        self,
        group: MentionGroup,
        decision: EmissionDecision,
        note: NoteInput,
        score: float,
        calibrated: bool,
        index: int,
        urls: ExtensionUrls,
    ) -> dict[str, Any] | None:
        """Build the resource for one group, then attach every evidence span."""
        cfg = self.config
        mention = group.mention
        best = group.best_grounding
        resource_id = f"{note.note_id}-{mention.mention_type.value[:4]}-{index}"

        if mention.mention_type is MentionType.CONDITION:
            resource = build_condition(
                mention,
                group.resolution,
                best,
                decision,
                note,
                confidence=score,
                calibrated=calibrated,
                resource_id=resource_id,
                include_quotes=cfg.include_quotes,
                include_category=cfg.include_category,
                urls=urls,
            )
            extra = add_condition_evidence
        elif mention.mention_type is MentionType.MEDICATION:
            authored = (
                resolve_date(mention.date_text, note.note_datetime) if mention.date_text else None
            )
            resource = build_medication_request(
                mention,
                group.resolution,
                best,
                decision,
                note,
                confidence=score,
                calibrated=calibrated,
                resource_id=resource_id,
                authored_on=authored,
                include_quotes=cfg.include_quotes,
                urls=urls,
            )
            extra = add_med_evidence
        elif mention.mention_type is MentionType.OBSERVATION:
            effective = (
                resolve_date(mention.date_text, note.note_datetime) if mention.date_text else None
            )
            if effective is None and cfg.infer_observation_effective:
                effective = inferred_from_note(note.note_datetime)
            value = parse_value(
                mention.value_text if mention.value_number is None else mention.value_number
            )
            resource = build_observation(
                mention,
                group.resolution,
                best,
                decision,
                note,
                confidence=score,
                calibrated=calibrated,
                resource_id=resource_id,
                value=value,
                effective=effective,
                include_quotes=cfg.include_quotes,
                mark_inferred_effective=cfg.mark_inferred_effective,
                urls=urls,
            )
            extra = add_obs_evidence
        else:  # pragma: no cover - MentionType is exhaustive
            return None

        # Every merged span, beyond the representative one already attached.
        for grounding in group.groundings:
            if grounding is best:
                continue
            extra(resource, grounding, note, include_quotes=cfg.include_quotes, urls=urls)
        return resource

run_note

run_note(note: NoteInput) -> NoteResult

Run the full pipeline on one note.

Source code in src/fhirground/pipeline.py
def run_note(self, note: NoteInput) -> NoteResult:
    """Run the full pipeline on one note."""
    cfg = self.config
    urls = cfg.extension_urls
    result = NoteResult(note=note)

    plan = chunk_note(
        note.text,
        note.note_id,
        max_chars=cfg.max_chars,
        overlap_chars=cfg.overlap_chars,
        section_headers=cfg.section_headers,
        respect_sections=cfg.respect_sections,
    )

    # --- extract ---------------------------------------------------
    raw_items: list[tuple[Mention, Resolution, Grounding, str, int]] = []
    sample_sets: list[list[tuple[Mention, Resolution]]] = []
    total_repairs = 0
    tokens_in = tokens_out = 0
    latency = 0.0
    n_mentions = 0

    for chunk in plan.chunks:
        extraction = extract_chunk(
            chunk,
            self.backend,
            self.schema,
            note_datetime=note.note_datetime.isoformat(),
            temperature=cfg.temperature,
            samples=cfg.samples,
            max_repairs=cfg.max_repairs,
            cache=self.cache,
            schema_digest=self.schema_digest,
        )
        total_repairs += extraction.repairs
        tokens_in += extraction.tokens_in
        tokens_out += extraction.tokens_out
        latency += extraction.latency_s

        if not extraction.ok:
            result.errors.append(
                f"chunk {chunk.chunk_id} failed after {extraction.repairs} repair(s): "
                f"{extraction.error}"
            )
            continue

        # Extra samples are kept only to measure consistency.
        for sample in extraction.samples[1:]:
            sample_sets.append(
                [(m, self.resolvers.resolve(m.text, m.mention_type)) for m in sample.mentions]
            )

        for mention in extraction.mentions.mentions:
            n_mentions += 1
            grounding = ground_mention(
                mention.evidence,
                plan.chunks,
                note.text,
                preferred_chunk_id=chunk.chunk_id,
                fuzzy_threshold=cfg.fuzzy_threshold,
            )
            if grounding is None:
                result.dropped.append((mention, DropReason.UNGROUNDED))
                result.debug.append(
                    MentionTrace(
                        mention=mention,
                        chunk_id=chunk.chunk_id,
                        drop_reason=DropReason.UNGROUNDED,
                    )
                )
                continue
            resolution = self.resolvers.resolve(mention.text, mention.mention_type)
            raw_items.append(
                (mention, resolution, grounding, chunk.chunk_id, extraction.repairs)
            )

    # --- dedup -----------------------------------------------------
    groups = dedup_mentions([(m, r, g) for m, r, g, _c, _rep in raw_items])
    repairs_by_key = {
        (m.mention_type.value, m.normalized_text, m.assertion.value): rep
        for m, _r, _g, _c, rep in raw_items
    }
    chunk_by_key = {
        (m.mention_type.value, m.normalized_text, m.assertion.value): c
        for m, _r, _g, c, _rep in raw_items
    }

    # --- policy, map, validate, score ------------------------------
    emitted: list[dict[str, Any]] = []
    for index, group in enumerate(groups):
        mention = group.mention
        identity = (
            mention.mention_type.value,
            mention.normalized_text,
            mention.assertion.value,
        )
        chunk_id = chunk_by_key.get(identity, "")
        repairs = repairs_by_key.get(identity, 0)
        best = group.best_grounding
        section = section_at(plan.sections, best.start)

        decision = decide(
            mention,
            emit_refuted=cfg.emit_refuted,
            section=section,
            respect_non_patient_sections=cfg.respect_non_patient_sections,
        )
        trace = MentionTrace(
            mention=mention,
            chunk_id=chunk_id,
            grounding=best,
            resolution=group.resolution,
            decision=decision,
            n_duplicates=group.n_duplicates,
        )

        if not decision.emit:
            reason = decision.reason or DropReason.UNSUPPORTED
            result.dropped.append((mention, reason))
            trace.drop_reason = reason
            result.debug.append(trace)
            continue

        components = self._components(group, repairs, sample_sets, n_samples=cfg.samples)
        score = aggregate(components, cfg.weights)
        calibrated = False
        if self.calibrator is not None and self.calibrator.fitted:
            score = self.calibrator.transform(score)
            calibrated = True

        trace.components = components
        trace.score = score
        trace.calibrated = calibrated

        if score < cfg.min_confidence:
            result.dropped.append((mention, DropReason.BELOW_THRESHOLD))
            trace.drop_reason = DropReason.BELOW_THRESHOLD
            result.debug.append(trace)
            continue

        resource = self._map(group, decision, note, score, calibrated, index, urls)
        if resource is None:
            result.dropped.append((mention, DropReason.UNSUPPORTED))
            trace.drop_reason = DropReason.UNSUPPORTED
            result.debug.append(trace)
            continue

        report = validate_resource(
            resource,
            note.text,
            urls=urls,
            require_quote_match=cfg.include_quotes,
        )
        trace.validation = report
        if not report.ok:
            result.dropped.append((mention, DropReason.VALIDATION_FAILED))
            trace.drop_reason = DropReason.VALIDATION_FAILED
            result.validation.extend(report)
            result.debug.append(trace)
            continue

        result.validation.extend(report)
        trace.resource_id = resource["id"]
        trace.resource_type = resource["resourceType"]
        emitted.append(resource)
        result.debug.append(trace)

    # --- provenance and bundle -------------------------------------
    if emitted:
        from fhirground import __version__
        from fhirground.validate import parse_with_models

        provenance = build_provenance(
            resource_id=f"prov-{note.note_id}",
            target_references=[f"{r['resourceType']}/{r['id']}" for r in emitted],
            source_reference=note.source_reference,
            patient_ref=note.patient_ref,
            model_id=getattr(self.backend, "model_id", "unknown"),
            prompt_version=PROMPT_VERSION,
            package_version=__version__,
            fhir_library=_fhir_library(),
            schema_digest=self.schema_digest,
            backend_name=getattr(self.backend, "name", "unknown"),
        )
        prov_report = parse_with_models(provenance)
        result.validation.extend(prov_report)
        if prov_report.ok:
            emitted.append(provenance)

    result.resources = emitted
    result.bundle = build_bundle(emitted, bundle_id=f"bundle-{note.note_id}")
    result.validation.extend(
        __import__("fhirground.validate", fromlist=["parse_with_models"]).parse_with_models(
            result.bundle
        )
    )

    result.stats = {
        "n_chunks": len(plan.chunks),
        "chunk_coverage": round(plan.coverage(len(note.text)), 6),
        "n_mentions": n_mentions,
        "n_groups": len(groups),
        "n_resources": len([r for r in emitted if r["resourceType"] != "Provenance"]),
        "n_dropped": len(result.dropped),
        "repairs": total_repairs,
        "tokens_in": tokens_in,
        "tokens_out": tokens_out,
        "latency_s": round(latency, 4),
        "drop_counts": result.drop_counts(),
        "resource_counts": result.resource_counts(),
    }
    return result

run

run(
    notes: Iterable[NoteInput], concurrency: int = 4
) -> Iterator[NoteResult]

Run over many notes.

Parameters:

Name Type Description Default
notes Iterable[NoteInput]

The notes.

required
concurrency int

Worker threads. The work is IO-bound on a backend call, so threads are the right tool. 1 runs inline, which keeps tracebacks readable while debugging.

4

Yields:

Name Type Description
One NoteResult

class:NoteResult per note, in input order.

Source code in src/fhirground/pipeline.py
def run(self, notes: Iterable[NoteInput], concurrency: int = 4) -> Iterator[NoteResult]:
    """Run over many notes.

    Args:
        notes: The notes.
        concurrency: Worker threads. The work is IO-bound on a backend
            call, so threads are the right tool. ``1`` runs inline, which
            keeps tracebacks readable while debugging.

    Yields:
        One :class:`NoteResult` per note, in input order.
    """
    note_list = list(notes)
    if concurrency <= 1:
        for note in note_list:
            yield self.run_note(note)
        return

    from concurrent.futures import ThreadPoolExecutor

    with ThreadPoolExecutor(max_workers=concurrency) as pool:
        yield from pool.map(self.run_note, note_list)

PipelineConfig

Bases: BaseModel

Everything that changes what the pipeline produces.

Source code in src/fhirground/pipeline.py
class PipelineConfig(BaseModel):
    """Everything that changes what the pipeline produces."""

    model_config = ConfigDict(extra="forbid")

    # extraction
    samples: int = Field(default=1, ge=1, le=16)
    temperature: float = Field(default=0.0, ge=0.0, le=2.0)
    max_repairs: int = Field(default=2, ge=0, le=5)

    # chunking
    max_chars: int = Field(default=2000, ge=50)
    overlap_chars: int = Field(default=200, ge=0)
    section_headers: tuple[str, ...] = DEFAULT_SECTION_HEADERS
    respect_sections: bool = True

    # grounding
    fuzzy_threshold: float = Field(default=DEFAULT_FUZZY_THRESHOLD, ge=0.0, le=100.0)

    # emission policy
    emit_refuted: bool = False
    respect_non_patient_sections: bool = True
    include_quotes: bool = True
    include_category: bool = False
    mark_inferred_effective: bool = True
    infer_observation_effective: bool = True

    # scoring
    min_confidence: float = Field(default=0.0, ge=0.0, le=1.0)
    weights: dict[str, float] | None = None

    # output
    extension_base_url: str | None = None

    # caching
    cache_path: Path | None = None

    def validate_consistency(self) -> None:
        """Catch combinations that cannot do what the caller intends.

        Raises:
            ConfigError: When the configuration is self-defeating rather than
                merely unusual.
        """
        if self.overlap_chars >= self.max_chars:
            raise ConfigError(
                f"overlap_chars ({self.overlap_chars}) must be smaller than max_chars "
                f"({self.max_chars}), or chunking cannot advance"
            )
        if self.samples > 1 and self.temperature == 0.0:
            raise ConfigError(
                f"samples={self.samples} with temperature=0.0 produces identical "
                "samples, so the self-consistency score would always be 1.0 and mean "
                "nothing. Raise the temperature or set samples=1."
            )

    @property
    def extension_urls(self) -> ExtensionUrls:
        """Resolved extension URLs."""
        return (
            ExtensionUrls(self.extension_base_url) if self.extension_base_url else ExtensionUrls()
        )

extension_urls property

extension_urls: ExtensionUrls

Resolved extension URLs.

validate_consistency

validate_consistency() -> None

Catch combinations that cannot do what the caller intends.

Raises:

Type Description
ConfigError

When the configuration is self-defeating rather than merely unusual.

Source code in src/fhirground/pipeline.py
def validate_consistency(self) -> None:
    """Catch combinations that cannot do what the caller intends.

    Raises:
        ConfigError: When the configuration is self-defeating rather than
            merely unusual.
    """
    if self.overlap_chars >= self.max_chars:
        raise ConfigError(
            f"overlap_chars ({self.overlap_chars}) must be smaller than max_chars "
            f"({self.max_chars}), or chunking cannot advance"
        )
    if self.samples > 1 and self.temperature == 0.0:
        raise ConfigError(
            f"samples={self.samples} with temperature=0.0 produces identical "
            "samples, so the self-consistency score would always be 1.0 and mean "
            "nothing. Raise the temperature or set samples=1."
        )

NoteResult dataclass

What one note produced.

Source code in src/fhirground/pipeline.py
@dataclass
class NoteResult:
    """What one note produced."""

    note: NoteInput
    bundle: dict[str, Any] = field(default_factory=dict)
    resources: list[dict[str, Any]] = field(default_factory=list)
    dropped: list[tuple[Mention, DropReason]] = field(default_factory=list)
    debug: list[MentionTrace] = field(default_factory=list)
    validation: ValidationReport = field(default_factory=ValidationReport)
    stats: dict[str, Any] = field(default_factory=dict)
    errors: list[str] = field(default_factory=list)

    @property
    def ok(self) -> bool:
        """Whether the note processed without a hard failure."""
        return not self.errors

    def by_type(self, resource_type: str) -> list[dict[str, Any]]:
        """Emitted resources of one type."""
        return [r for r in self.resources if r.get("resourceType") == resource_type]

    def drop_counts(self) -> dict[str, int]:
        """Dropped mention counts per reason, every reason present."""
        counts = {r.value: 0 for r in DropReason}
        for _mention, reason in self.dropped:
            counts[reason.value] = counts.get(reason.value, 0) + 1
        return counts

    def resource_counts(self) -> dict[str, int]:
        """Emitted resource counts per type."""
        counts: dict[str, int] = {}
        for resource in self.resources:
            key = str(resource.get("resourceType"))
            counts[key] = counts.get(key, 0) + 1
        return counts

ok property

ok: bool

Whether the note processed without a hard failure.

by_type

by_type(resource_type: str) -> list[dict[str, Any]]

Emitted resources of one type.

Source code in src/fhirground/pipeline.py
def by_type(self, resource_type: str) -> list[dict[str, Any]]:
    """Emitted resources of one type."""
    return [r for r in self.resources if r.get("resourceType") == resource_type]

drop_counts

drop_counts() -> dict[str, int]

Dropped mention counts per reason, every reason present.

Source code in src/fhirground/pipeline.py
def drop_counts(self) -> dict[str, int]:
    """Dropped mention counts per reason, every reason present."""
    counts = {r.value: 0 for r in DropReason}
    for _mention, reason in self.dropped:
        counts[reason.value] = counts.get(reason.value, 0) + 1
    return counts

resource_counts

resource_counts() -> dict[str, int]

Emitted resource counts per type.

Source code in src/fhirground/pipeline.py
def resource_counts(self) -> dict[str, int]:
    """Emitted resource counts per type."""
    counts: dict[str, int] = {}
    for resource in self.resources:
        key = str(resource.get("resourceType"))
        counts[key] = counts.get(key, 0) + 1
    return counts

MentionTrace dataclass

Everything that happened to one mention, for the debug output.

Source code in src/fhirground/pipeline.py
@dataclass
class MentionTrace:
    """Everything that happened to one mention, for the debug output."""

    mention: Mention
    chunk_id: str
    grounding: Grounding | None = None
    resolution: Resolution | None = None
    decision: EmissionDecision | None = None
    components: ConfidenceComponents | None = None
    score: float | None = None
    calibrated: bool = False
    resource_id: str | None = None
    resource_type: str | None = None
    drop_reason: DropReason | None = None
    validation: ValidationReport | None = None
    n_duplicates: int = 0

    def as_dict(self) -> dict[str, Any]:
        """JSON-safe trace row."""
        return {
            "mention": self.mention.model_dump(mode="json", exclude_none=True),
            "chunk_id": self.chunk_id,
            "grounding": (
                {
                    "start": self.grounding.start,
                    "end": self.grounding.end,
                    "strategy": self.grounding.strategy.value,
                    "score": self.grounding.score,
                    "ambiguous": self.grounding.ambiguous,
                }
                if self.grounding
                else None
            ),
            "resolution": (
                {
                    "coded": self.resolution.is_coded,
                    "system": self.resolution.coding.system if self.resolution.coding else None,
                    "code": self.resolution.coding.code if self.resolution.coding else None,
                    "score": self.resolution.score,
                    "resolver": self.resolution.resolver,
                    "method": self.resolution.method,
                }
                if self.resolution
                else None
            ),
            "decision": (
                {
                    "emit": self.decision.emit,
                    "reason": self.decision.reason.value if self.decision.reason else None,
                    "note": self.decision.note,
                }
                if self.decision
                else None
            ),
            "confidence_components": self.components.as_dict() if self.components else None,
            "score": self.score,
            "calibrated": self.calibrated,
            "resource_type": self.resource_type,
            "resource_id": self.resource_id,
            "drop_reason": self.drop_reason.value if self.drop_reason else None,
            "n_duplicates": self.n_duplicates,
            "validation": self.validation.as_dict() if self.validation else None,
        }

as_dict

as_dict() -> dict[str, Any]

JSON-safe trace row.

Source code in src/fhirground/pipeline.py
def as_dict(self) -> dict[str, Any]:
    """JSON-safe trace row."""
    return {
        "mention": self.mention.model_dump(mode="json", exclude_none=True),
        "chunk_id": self.chunk_id,
        "grounding": (
            {
                "start": self.grounding.start,
                "end": self.grounding.end,
                "strategy": self.grounding.strategy.value,
                "score": self.grounding.score,
                "ambiguous": self.grounding.ambiguous,
            }
            if self.grounding
            else None
        ),
        "resolution": (
            {
                "coded": self.resolution.is_coded,
                "system": self.resolution.coding.system if self.resolution.coding else None,
                "code": self.resolution.coding.code if self.resolution.coding else None,
                "score": self.resolution.score,
                "resolver": self.resolution.resolver,
                "method": self.resolution.method,
            }
            if self.resolution
            else None
        ),
        "decision": (
            {
                "emit": self.decision.emit,
                "reason": self.decision.reason.value if self.decision.reason else None,
                "note": self.decision.note,
            }
            if self.decision
            else None
        ),
        "confidence_components": self.components.as_dict() if self.components else None,
        "score": self.score,
        "calibrated": self.calibrated,
        "resource_type": self.resource_type,
        "resource_id": self.resource_id,
        "drop_reason": self.drop_reason.value if self.drop_reason else None,
        "n_duplicates": self.n_duplicates,
        "validation": self.validation.as_dict() if self.validation else None,
    }

run_notes

run_notes(
    notes: Iterable[NoteInput],
    backend: Backend,
    *,
    config: PipelineConfig | None = None,
    resolvers: ResolverConfig | None = None,
    calibrator: Calibrator | None = None,
    concurrency: int = 4,
) -> list[NoteResult]

Convenience wrapper: build a Pipeline and run it to completion.

Source code in src/fhirground/pipeline.py
def run_notes(
    notes: Iterable[NoteInput],
    backend: Backend,
    *,
    config: PipelineConfig | None = None,
    resolvers: ResolverConfig | None = None,
    calibrator: Calibrator | None = None,
    concurrency: int = 4,
) -> list[NoteResult]:
    """Convenience wrapper: build a Pipeline and run it to completion."""
    pipe = Pipeline(config, backend=backend, resolvers=resolvers, calibrator=calibrator)
    return list(pipe.run(notes, concurrency=concurrency))

summarize

summarize(
    results: list[NoteResult],
    *,
    started: datetime | None = None,
) -> dict[str, Any]

Aggregate a run into the run_summary.json shape (SPEC §6.4).

Source code in src/fhirground/pipeline.py
def summarize(results: list[NoteResult], *, started: datetime | None = None) -> dict[str, Any]:
    """Aggregate a run into the ``run_summary.json`` shape (SPEC §6.4)."""
    from fhirground import __version__

    resource_counts: dict[str, int] = {}
    drop_counts: dict[str, int] = {r.value: 0 for r in DropReason}
    tokens_in = tokens_out = repairs = n_mentions = 0
    latency = 0.0
    n_errors = 0

    for result in results:
        for key, value in result.resource_counts().items():
            resource_counts[key] = resource_counts.get(key, 0) + value
        for key, value in result.drop_counts().items():
            drop_counts[key] = drop_counts.get(key, 0) + value
        stats = result.stats
        tokens_in += int(stats.get("tokens_in") or 0)
        tokens_out += int(stats.get("tokens_out") or 0)
        repairs += int(stats.get("repairs") or 0)
        n_mentions += int(stats.get("n_mentions") or 0)
        latency += float(stats.get("latency_s") or 0.0)
        n_errors += len(result.errors)

    return {
        "n_notes": len(results),
        "n_notes_with_errors": sum(1 for r in results if r.errors),
        "n_mentions": n_mentions,
        "resource_counts": resource_counts,
        "drop_counts": drop_counts,
        "repairs": repairs,
        "tokens_in": tokens_in,
        "tokens_out": tokens_out,
        "latency_s": round(latency, 4),
        "n_validation_errors": sum(len(r.validation.errors) for r in results),
        "n_validation_warnings": sum(len(r.validation.warnings) for r in results),
        "n_errors": n_errors,
        "versions": {
            "fhirground": __version__,
            "prompt": PROMPT_VERSION,
            "fhir_library": _fhir_library(),
        },
        "started": started.isoformat() if started else None,
    }

Input

fhirground.io

Input: notes from JSONL, or from FHIR DocumentReference resources.

Two input shapes, one model. NoteInput is what the pipeline consumes; everything here exists to produce one.

patient_ref is required, not optional. Every resource fhirground emits needs a subject, and a FHIR resource without a subject is not useful to anyone. Failing at read time with a clear message beats discovering it during mapping.

NoteInput

Bases: BaseModel

One clinical note plus the metadata needed to emit FHIR from it.

Source code in src/fhirground/io.py
class NoteInput(BaseModel):
    """One clinical note plus the metadata needed to emit FHIR from it."""

    model_config = ConfigDict(extra="forbid")

    note_id: str = Field(min_length=1)
    patient_ref: str = Field(
        min_length=1,
        description="FHIR reference such as 'Patient/123'. Required: every emitted "
        "resource needs a subject.",
    )
    note_datetime: datetime = Field(
        description="When the note was written. Anchors relative date resolution."
    )
    text: str = Field(min_length=1)
    encounter_ref: str | None = None
    document_reference_id: str | None = Field(
        default=None,
        description="Id of the source DocumentReference, referenced by evidence extensions.",
    )

    @field_validator("note_id", "patient_ref", mode="before")
    @classmethod
    def _strip(cls, v: object) -> object:
        return v.strip() if isinstance(v, str) else v

    @field_validator("patient_ref")
    @classmethod
    def _check_reference_shape(cls, v: str) -> str:
        """Warn-by-raising on a bare id.

        ``123`` is not a FHIR reference and would produce a resource whose
        subject does not resolve. Requiring ``ResourceType/id`` here is
        cheaper than debugging a Bundle later.
        """
        if "/" not in v:
            raise ValueError(f"patient_ref must be a FHIR reference like 'Patient/{v}', got {v!r}")
        return v

    @property
    def source_reference(self) -> str | None:
        """Reference to the source DocumentReference, if one was given."""
        if self.document_reference_id is None:
            return None
        if "/" in self.document_reference_id:
            return self.document_reference_id
        return f"DocumentReference/{self.document_reference_id}"

    def text_hash(self) -> str:
        """SHA-256 of the note text, for logs that must not contain the text."""
        import hashlib

        return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:16]

source_reference property

source_reference: str | None

Reference to the source DocumentReference, if one was given.

text_hash

text_hash() -> str

SHA-256 of the note text, for logs that must not contain the text.

Source code in src/fhirground/io.py
def text_hash(self) -> str:
    """SHA-256 of the note text, for logs that must not contain the text."""
    import hashlib

    return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:16]

read_notes

read_notes(
    path: str | Path, input_format: str = "jsonl"
) -> list[NoteInput]

Read notes in either supported format.

Parameters:

Name Type Description Default
path str | Path

File or directory.

required
input_format str

"jsonl" or "fhir".

'jsonl'
Source code in src/fhirground/io.py
def read_notes(path: str | Path, input_format: str = "jsonl") -> list[NoteInput]:
    """Read notes in either supported format.

    Args:
        path: File or directory.
        input_format: ``"jsonl"`` or ``"fhir"``.
    """
    if input_format == "jsonl":
        return read_notes_jsonl(path)
    if input_format == "fhir":
        return read_notes_fhir(path)
    raise InputError(f"unknown input format {input_format!r}; use 'jsonl' or 'fhir'")

read_notes_jsonl

read_notes_jsonl(path: str | Path) -> list[NoteInput]

Read notes from JSONL, one object per line.

Raises:

Type Description
InputError

On a missing file, malformed JSON, or a record that fails validation. The message carries the path and 1-based line number.

Source code in src/fhirground/io.py
def read_notes_jsonl(path: str | Path) -> list[NoteInput]:
    """Read notes from JSONL, one object per line.

    Raises:
        InputError: On a missing file, malformed JSON, or a record that fails
            validation. The message carries the path and 1-based line number.
    """
    path = Path(path)
    if not path.exists():
        raise InputError("notes file not found", path=str(path))

    out: list[NoteInput] = []
    seen: set[str] = set()
    with path.open(encoding="utf-8") as fh:
        for lineno, raw in enumerate(fh, start=1):
            stripped = raw.strip()
            if not stripped or stripped.startswith("//"):
                continue
            try:
                obj = json.loads(stripped)
            except json.JSONDecodeError as exc:
                raise InputError(f"malformed JSON: {exc.msg}", path=str(path), line=lineno) from exc
            if not isinstance(obj, dict):
                raise InputError(
                    f"each line must be a JSON object, got {type(obj).__name__}",
                    path=str(path),
                    line=lineno,
                )
            try:
                note = NoteInput.model_validate(obj)
            except Exception as exc:
                raise InputError(
                    f"invalid note: {_pydantic_detail(exc)}", path=str(path), line=lineno
                ) from exc
            if note.note_id in seen:
                raise InputError(
                    f"duplicate note_id {note.note_id!r}; note ids must be unique",
                    path=str(path),
                    line=lineno,
                )
            seen.add(note.note_id)
            out.append(note)

    if not out:
        raise InputError("notes file contained no records", path=str(path))
    return out

read_notes_fhir

read_notes_fhir(path: str | Path) -> list[NoteInput]

Read notes from FHIR DocumentReference resources or Bundles.

Accepts a single JSON file or a directory of them, which is the shape Synthea writes. Resources that are not DocumentReferences, and DocumentReferences with no readable text/plain attachment, are skipped rather than treated as errors -- a Synthea bundle is full of both.

Raises:

Type Description
InputError

If nothing usable was found, or a DocumentReference is missing the subject or date that makes it usable at all.

Source code in src/fhirground/io.py
def read_notes_fhir(path: str | Path) -> list[NoteInput]:
    """Read notes from FHIR ``DocumentReference`` resources or Bundles.

    Accepts a single JSON file or a directory of them, which is the shape
    Synthea writes. Resources that are not DocumentReferences, and
    DocumentReferences with no readable ``text/plain`` attachment, are skipped
    rather than treated as errors -- a Synthea bundle is full of both.

    Raises:
        InputError: If nothing usable was found, or a DocumentReference is
            missing the subject or date that makes it usable at all.
    """
    path = Path(path)
    if not path.exists():
        raise InputError("FHIR input path not found", path=str(path))

    files = sorted(path.glob("**/*.json")) if path.is_dir() else [path]
    if not files:
        raise InputError("no .json files found", path=str(path))

    out: list[NoteInput] = []
    seen: set[str] = set()
    for file in files:
        try:
            doc = json.loads(file.read_text(encoding="utf-8"))
        except json.JSONDecodeError as exc:
            raise InputError(f"malformed JSON: {exc.msg}", path=str(file)) from exc

        for resource in _iter_resources(doc):
            if resource.get("resourceType") != "DocumentReference":
                continue
            note = _note_from_document_reference(resource, path=str(file))
            if note is None:
                continue
            if note.note_id in seen:
                continue
            seen.add(note.note_id)
            out.append(note)

    if not out:
        raise InputError(
            "no DocumentReference with a readable text/plain attachment was found. "
            f"Looked in {len(files)} file(s). Synthea must be run with text notes "
            "enabled, or use --input-format jsonl instead",
            path=str(path),
        )
    return out

write_notes_jsonl

write_notes_jsonl(
    notes: Iterable[NoteInput], path: str | Path
) -> int

Write notes as JSONL. Returns the number written.

Source code in src/fhirground/io.py
def write_notes_jsonl(notes: Iterable[NoteInput], path: str | Path) -> int:
    """Write notes as JSONL. Returns the number written."""
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    n = 0
    with target.open("w", encoding="utf-8") as fh:
        for note in notes:
            fh.write(note.model_dump_json(exclude_none=True))
            fh.write("\n")
            n += 1
    return n

The mention schema

fhirground.schemas.mention

The mention schema: what the LLM is allowed to say.

This is the narrow waist of the whole design. The model produces mentions -- plain-language findings with a verbatim evidence quote -- and deterministic code produces FHIR. FHIR structure never depends on the model's formatting.

There are no code fields here, by design. A model cannot emit a SNOMED, LOINC, or RxNorm code through this schema because the schema has nowhere to put one. Codes enter only through a :class:~fhirground.terminology.base.TerminologyResolver, and the mapping functions accept only :class:~fhirground.terminology.base.Resolution objects, never raw strings. A property test asserts the invariant over adversarial input.

The JSON Schema generated from these models is the constrained-decoding target for both backends, so it stays inside the subset Bedrock tool inputSchema and vLLM guided decoding both accept: flat objects, enums, nullable fields via type unions, no oneOf/anyOf on objects, and no $ref recursion.

Mention

Bases: BaseModel

One finding the model claims the note contains.

Only four fields are required. Everything else is optional because a model that must fill every field will invent values for the ones it cannot support -- and an invented dose is worse than a missing one.

Source code in src/fhirground/schemas/mention.py
class Mention(BaseModel):
    """One finding the model claims the note contains.

    Only four fields are required. Everything else is optional because a model
    that must fill every field will invent values for the ones it cannot
    support -- and an invented dose is worse than a missing one.
    """

    model_config = ConfigDict(extra="forbid", use_enum_values=False)

    mention_type: MentionType
    text: str = Field(
        min_length=1,
        max_length=MAX_TEXT_LEN,
        description="The concept as the note expresses it, in plain language.",
    )
    evidence: str = Field(
        min_length=1,
        max_length=MAX_EVIDENCE_LEN,
        description="Verbatim quote copied from the note. Must appear in the note text.",
    )
    assertion: Assertion

    # -- condition ------------------------------------------------------
    clinical_status_hint: ClinicalStatusHint | None = None
    onset_text: str | None = Field(
        default=None,
        max_length=MAX_TEXT_LEN,
        description="Onset as the note expresses it, e.g. 'since 2019'.",
    )

    # -- medication -----------------------------------------------------
    med_action: MedAction | None = None
    dose_value: float | None = None
    dose_unit: str | None = Field(default=None, max_length=50)
    route: str | None = Field(default=None, max_length=50)
    frequency_text: str | None = Field(default=None, max_length=100)

    # -- observation ----------------------------------------------------
    obs_category: ObsCategory | None = None
    value_number: float | None = None
    value_comparator: ValueComparator | None = None
    value_text: str | None = Field(default=None, max_length=MAX_TEXT_LEN)
    value_unit: str | None = Field(default=None, max_length=50)
    date_text: str | None = Field(
        default=None,
        max_length=MAX_TEXT_LEN,
        description="Date or relative phrase as written, e.g. '3 days ago'.",
    )

    @field_validator("text", "evidence", mode="before")
    @classmethod
    def _strip(cls, v: object) -> object:
        return v.strip() if isinstance(v, str) else v

    @field_validator(
        "onset_text",
        "dose_unit",
        "route",
        "frequency_text",
        "value_text",
        "value_unit",
        "date_text",
        mode="before",
    )
    @classmethod
    def _blank_to_none(cls, v: object) -> object:
        """Treat an empty or whitespace-only optional string as absent.

        Models frequently emit ``""`` instead of ``null`` for a field they have
        nothing to say about. Carrying that through would produce a FHIR
        resource with an empty ``route.text``.
        """
        if isinstance(v, str):
            s = v.strip()
            return s if s else None
        return v

    @property
    def normalized_text(self) -> str:
        """Lower-cased, whitespace-collapsed surface form, for deduplication."""
        return " ".join(self.text.lower().split())

normalized_text property

normalized_text: str

Lower-cased, whitespace-collapsed surface form, for deduplication.

MentionList

Bases: BaseModel

The complete model response: a list of mentions and nothing else.

Source code in src/fhirground/schemas/mention.py
class MentionList(BaseModel):
    """The complete model response: a list of mentions and nothing else."""

    model_config = ConfigDict(extra="forbid")

    mentions: list[Mention] = Field(default_factory=list)

    def __len__(self) -> int:
        return len(self.mentions)

    def __iter__(self) -> Any:  # type: ignore[override]
        return iter(self.mentions)

    def by_type(self, mention_type: MentionType) -> list[Mention]:
        """Mentions of one type, in order."""
        return [m for m in self.mentions if m.mention_type is mention_type]

by_type

by_type(mention_type: MentionType) -> list[Mention]

Mentions of one type, in order.

Source code in src/fhirground/schemas/mention.py
def by_type(self, mention_type: MentionType) -> list[Mention]:
    """Mentions of one type, in order."""
    return [m for m in self.mentions if m.mention_type is mention_type]

MentionType

Bases: StrEnum

The three things v1 extracts.

Source code in src/fhirground/schemas/mention.py
class MentionType(StrEnum):
    """The three things v1 extracts."""

    CONDITION = "condition"
    MEDICATION = "medication"
    OBSERVATION = "observation"

Assertion

Bases: StrEnum

How the note asserts the finding.

This is the field that keeps negated and family-history mentions from becoming affirmed facts. The emission policy per value is in :mod:fhirground.assertion.

Source code in src/fhirground/schemas/mention.py
class Assertion(StrEnum):
    """How the note asserts the finding.

    This is the field that keeps negated and family-history mentions from
    becoming affirmed facts. The emission policy per value is in
    :mod:`fhirground.assertion`.
    """

    PRESENT = "present"
    NEGATED = "negated"
    POSSIBLE = "possible"
    HISTORICAL = "historical"
    FAMILY = "family"
    HYPOTHETICAL = "hypothetical"

ClinicalStatusHint

Bases: StrEnum

An optional hint at FHIR Condition.clinicalStatus.

A hint, not an assignment: the mapper decides whether to use it, and omits clinicalStatus entirely when there is no hint rather than guessing active.

Source code in src/fhirground/schemas/mention.py
class ClinicalStatusHint(StrEnum):
    """An optional hint at FHIR ``Condition.clinicalStatus``.

    A hint, not an assignment: the mapper decides whether to use it, and omits
    ``clinicalStatus`` entirely when there is no hint rather than guessing
    ``active``.
    """

    ACTIVE = "active"
    RESOLVED = "resolved"
    INACTIVE = "inactive"
    REMISSION = "remission"

MedAction

Bases: StrEnum

What the note says is being done with a medication.

Source code in src/fhirground/schemas/mention.py
class MedAction(StrEnum):
    """What the note says is being done with a medication."""

    START = "start"
    CONTINUE = "continue"
    CHANGE = "change"
    STOP = "stop"
    MENTION = "mention"

ObsCategory

Bases: StrEnum

FHIR observation category, restricted to the two v1 supports.

Source code in src/fhirground/schemas/mention.py
class ObsCategory(StrEnum):
    """FHIR observation category, restricted to the two v1 supports."""

    VITAL_SIGNS = "vital-signs"
    LABORATORY = "laboratory"

ValueComparator

Bases: StrEnum

FHIR Quantity.comparator values.

Source code in src/fhirground/schemas/mention.py
class ValueComparator(StrEnum):
    """FHIR ``Quantity.comparator`` values."""

    LT = "<"
    LE = "<="
    GT = ">"
    GE = ">="

assert_no_code_fields

assert_no_code_fields() -> None

Raise if the mention schema has acquired a code-bearing field.

Called by a test rather than at import time, so the check is visible in the suite rather than being a silent side effect.

Source code in src/fhirground/schemas/mention.py
def assert_no_code_fields() -> None:
    """Raise if the mention schema has acquired a code-bearing field.

    Called by a test rather than at import time, so the check is visible in the
    suite rather than being a silent side effect.
    """
    offenders = {
        name for name in MENTION_FIELDS for bad in FORBIDDEN_FIELD_SUBSTRINGS if bad in name.lower()
    }
    if offenders:
        raise AssertionError(
            "the mention schema must contain no code fields (SPEC §0 hard rule), "
            f"but found: {sorted(offenders)}. Codes may only enter through a "
            "TerminologyResolver."
        )

fhirground.schemas.jsonschema

Generating the constrained-decoding schema from the Pydantic model.

Pydantic's model_json_schema() is not usable as a constrained-decoding target as-is. It emits $defs with $ref pointers for every enum, and expresses optionality as anyOf: [{...}, {"type": "null"}]. SPEC §6.1 requires the schema stay inside the subset that both Bedrock tool inputSchema and vLLM guided decoding accept: flat objects, enums, nullable fields via type unions, no oneOf/anyOf on objects, no $ref.

So this module takes pydantic's output and:

  1. inlines every $ref from $defs and deletes $defs;
  2. collapses anyOf: [{"type": "string"}, {"type": "null"}] into {"type": ["string", "null"]};
  3. collapses a nullable enum into one enum list containing null;
  4. strips pydantic bookkeeping (title, default, $schema noise) that adds nothing for a decoder and differs between pydantic versions;
  5. re-checks the result against :func:assert_backend_safe, so a future pydantic release that changes its output shape fails loudly here rather than at a backend.

The generated schema is checked in as mention.schema.json and a test asserts the file still matches what the model produces.

build_mention_schema

build_mention_schema() -> dict[str, Any]

Generate the backend-safe mention JSON Schema from the Pydantic model.

Returns:

Type Description
dict[str, Any]

A schema document ready to hand to a Bedrock tool inputSchema or an

dict[str, Any]

OpenAI-compatible response_format.json_schema.schema.

Source code in src/fhirground/schemas/jsonschema.py
def build_mention_schema() -> dict[str, Any]:
    """Generate the backend-safe mention JSON Schema from the Pydantic model.

    Returns:
        A schema document ready to hand to a Bedrock tool ``inputSchema`` or an
        OpenAI-compatible ``response_format.json_schema.schema``.
    """
    raw = MentionList.model_json_schema(mode="serialization")
    defs = raw.pop("$defs", {})
    schema = _inline_refs(raw, defs)
    schema = _collapse_nullable(schema)
    schema = _strip_noise(schema)

    schema["$schema"] = "https://json-schema.org/draft/2020-12/schema"
    schema["title"] = "MentionList"
    schema["additionalProperties"] = False
    schema.setdefault("type", "object")
    schema["required"] = ["mentions"]

    items = schema.get("properties", {}).get("mentions", {}).get("items")
    if isinstance(items, dict):
        items["additionalProperties"] = False
        # SPEC §6.1: exactly these four are required of a mention.
        items["required"] = ["mention_type", "text", "evidence", "assertion"]

    assert_backend_safe(schema)
    return schema

load_mention_schema

load_mention_schema() -> dict[str, Any]

Load the checked-in schema, falling back to generating it.

The file is the artifact users and backends see; generating on the fly is the fallback for an editable checkout where it has not been written yet.

Source code in src/fhirground/schemas/jsonschema.py
def load_mention_schema() -> dict[str, Any]:
    """Load the checked-in schema, falling back to generating it.

    The file is the artifact users and backends see; generating on the fly is
    the fallback for an editable checkout where it has not been written yet.
    """
    if SCHEMA_PATH.exists():
        return json.loads(SCHEMA_PATH.read_text())  # type: ignore[no-any-return]
    return build_mention_schema()

write_mention_schema

write_mention_schema(
    path: Path | str | None = None,
) -> Path

Write the generated schema to disk, formatted stably.

Source code in src/fhirground/schemas/jsonschema.py
def write_mention_schema(path: Path | str | None = None) -> Path:
    """Write the generated schema to disk, formatted stably."""
    target = Path(path) if path else SCHEMA_PATH
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(build_mention_schema(), indent=2, sort_keys=True) + "\n")
    return target

assert_backend_safe

assert_backend_safe(
    schema: dict[str, Any], *, path: str = "$"
) -> None

Raise if schema leaves the subset both backends accept.

Checks for the constructs SPEC §6.1 rules out. This is a real guard, not a formality: a $ref that reaches Bedrock produces an opaque validation error at request time, far from the cause.

Raises:

Type Description
ValueError

naming the offending key and its JSON path.

Source code in src/fhirground/schemas/jsonschema.py
def assert_backend_safe(schema: dict[str, Any], *, path: str = "$") -> None:
    """Raise if ``schema`` leaves the subset both backends accept.

    Checks for the constructs SPEC §6.1 rules out. This is a real guard, not a
    formality: a ``$ref`` that reaches Bedrock produces an opaque validation
    error at request time, far from the cause.

    Raises:
        ValueError: naming the offending key and its JSON path.
    """
    if isinstance(schema, dict):
        for bad in _FORBIDDEN_KEYS:
            if bad in schema:
                raise ValueError(
                    f"schema contains {bad!r} at {path}, which is outside the subset "
                    "accepted by both Bedrock tool inputSchema and vLLM guided decoding "
                    "(SPEC §6.1)"
                )
        if "anyOf" in schema:
            raise ValueError(
                f"schema contains 'anyOf' at {path}; express optionality as a type "
                "union such as {'type': ['string', 'null']} instead"
            )
        for key, value in schema.items():
            assert_backend_safe(value, path=f"{path}.{key}")
    elif isinstance(schema, list):
        for i, value in enumerate(schema):
            assert_backend_safe(value, path=f"{path}[{i}]")

schema_digest

schema_digest(schema: dict[str, Any] | None = None) -> str

Short SHA-256 of the canonical schema, recorded in run summaries.

Lets a reader tell whether two runs targeted the same decoding schema.

Source code in src/fhirground/schemas/jsonschema.py
def schema_digest(schema: dict[str, Any] | None = None) -> str:
    """Short SHA-256 of the canonical schema, recorded in run summaries.

    Lets a reader tell whether two runs targeted the same decoding schema.
    """
    import hashlib

    blob = json.dumps(schema or build_mention_schema(), sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode()).hexdigest()[:16]

Preprocessing

fhirground.preprocess.sections

Section-header detection.

Regex-based and configurable. Not a clinical document parser: it finds lines that look like ASSESSMENT: or Past Medical History: and records where they start. The section a mention came from is useful context for assertion (a finding under "Family History" is family history even when the sentence does not say so) and it goes into the debug trace.

Deliberately conservative. A missed header costs a little context; a false header could split a sentence across chunks and break grounding.

Section dataclass

A detected section header and the span of text under it.

Attributes:

Name Type Description
name str

Normalized header name, lower-cased.

header_start int

Offset of the header in the original text.

start int

Offset where the section body begins (just after the header).

end int

Offset where the body ends, which is the next header or the end of the note.

Source code in src/fhirground/preprocess/sections.py
@dataclass(frozen=True, slots=True)
class Section:
    """A detected section header and the span of text under it.

    Attributes:
        name: Normalized header name, lower-cased.
        header_start: Offset of the header in the original text.
        start: Offset where the section body begins (just after the header).
        end: Offset where the body ends, which is the next header or the end
            of the note.
    """

    name: str
    header_start: int
    start: int
    end: int

    def contains(self, offset: int) -> bool:
        """Whether an original-text offset falls under this section.

        Measured from ``header_start``, not ``start``, so the header line
        itself belongs to the section it names. Chunks are cut *at* header
        boundaries, so a body-only range would leave every chunk's first
        offset belonging to no section at all.
        """
        return self.header_start <= offset < self.end

    def contains_body(self, offset: int) -> bool:
        """Whether an offset falls in the section's body, excluding its header."""
        return self.start <= offset < self.end

contains

contains(offset: int) -> bool

Whether an original-text offset falls under this section.

Measured from header_start, not start, so the header line itself belongs to the section it names. Chunks are cut at header boundaries, so a body-only range would leave every chunk's first offset belonging to no section at all.

Source code in src/fhirground/preprocess/sections.py
def contains(self, offset: int) -> bool:
    """Whether an original-text offset falls under this section.

    Measured from ``header_start``, not ``start``, so the header line
    itself belongs to the section it names. Chunks are cut *at* header
    boundaries, so a body-only range would leave every chunk's first
    offset belonging to no section at all.
    """
    return self.header_start <= offset < self.end

contains_body

contains_body(offset: int) -> bool

Whether an offset falls in the section's body, excluding its header.

Source code in src/fhirground/preprocess/sections.py
def contains_body(self, offset: int) -> bool:
    """Whether an offset falls in the section's body, excluding its header."""
    return self.start <= offset < self.end

detect_sections

detect_sections(
    text: str,
    headers: tuple[str, ...] = DEFAULT_SECTION_HEADERS,
) -> list[Section]

Find section headers and the spans they govern.

Parameters:

Name Type Description Default
text str

The original note text.

required
headers tuple[str, ...]

Header names to look for.

DEFAULT_SECTION_HEADERS

Returns:

Type Description
list[Section]

Sections in document order. Empty when no header matched -- a note

list[Section]

with no headers is normal and is treated as one unnamed span by

list[Section]

callers.

Source code in src/fhirground/preprocess/sections.py
def detect_sections(text: str, headers: tuple[str, ...] = DEFAULT_SECTION_HEADERS) -> list[Section]:
    """Find section headers and the spans they govern.

    Args:
        text: The original note text.
        headers: Header names to look for.

    Returns:
        Sections in document order. Empty when no header matched -- a note
        with no headers is normal and is treated as one unnamed span by
        callers.
    """
    if not text or not headers:
        return []

    pattern = _build_pattern(tuple(headers))
    found: list[tuple[str, int, int]] = []
    for match in pattern.finditer(text):
        name = (match.group("name") or match.group("name2") or "").strip().lower()
        name = " ".join(name.split())
        found.append((name, match.start(), match.end()))

    sections: list[Section] = []
    for i, (name, header_start, body_start) in enumerate(found):
        end = found[i + 1][1] if i + 1 < len(found) else len(text)
        sections.append(Section(name=name, header_start=header_start, start=body_start, end=end))
    return sections

section_at

section_at(
    sections: list[Section], offset: int
) -> str | None

Name of the section containing offset, or None.

Searched in reverse so the innermost (latest-starting) section wins when spans touch.

Source code in src/fhirground/preprocess/sections.py
def section_at(sections: list[Section], offset: int) -> str | None:
    """Name of the section containing ``offset``, or None.

    Searched in reverse so the innermost (latest-starting) section wins when
    spans touch.
    """
    for section in reversed(sections):
        if section.contains(offset):
            return section.name
    return None

is_non_patient_section

is_non_patient_section(name: str | None) -> bool

Whether a section name implies the findings are not the patient's own.

Source code in src/fhirground/preprocess/sections.py
def is_non_patient_section(name: str | None) -> bool:
    """Whether a section name implies the findings are not the patient's own."""
    return name is not None and name in NON_PATIENT_SECTIONS

fhirground.preprocess.chunking

Chunking with exact offset bookkeeping.

The invariant this module exists to guarantee:

original_text[chunk.start_offset + i] == chunk.text[i]    for all valid i

Every evidence offset fhirground emits traces back to the original note through that identity. Chunk text is therefore a verbatim slice -- never stripped, normalized, or re-joined. A single stripped character would shift every offset downstream of it, and the resulting FHIR would point at the wrong words while looking perfectly valid.

A property test asserts the identity over generated text and chunk parameters.

Chunk dataclass

A verbatim slice of the original note text.

Attributes:

Name Type Description
chunk_id str

Stable identifier, <note_id>#<index>.

index int

Position in the note, 0-based.

text str

The slice itself, byte-for-byte from the original.

start_offset int

Where the slice starts in the original text.

end_offset int

Where it ends (exclusive).

section str | None

Name of the section the slice starts in, if any.

Source code in src/fhirground/preprocess/chunking.py
@dataclass(frozen=True, slots=True)
class Chunk:
    """A verbatim slice of the original note text.

    Attributes:
        chunk_id: Stable identifier, ``<note_id>#<index>``.
        index: Position in the note, 0-based.
        text: The slice itself, byte-for-byte from the original.
        start_offset: Where the slice starts in the original text.
        end_offset: Where it ends (exclusive).
        section: Name of the section the slice starts in, if any.
    """

    chunk_id: str
    index: int
    text: str
    start_offset: int
    end_offset: int
    section: str | None = None

    def __len__(self) -> int:
        return len(self.text)

    def to_original(self, local_offset: int) -> int:
        """Map an offset inside this chunk to the original text.

        Raises:
            ValueError: If the offset is outside the chunk, which would
                otherwise produce a plausible-looking but wrong global offset.
        """
        if not 0 <= local_offset <= len(self.text):
            raise ValueError(
                f"local offset {local_offset} is outside chunk {self.chunk_id} "
                f"of length {len(self.text)}"
            )
        return self.start_offset + local_offset

    def verify_against(self, original: str) -> None:
        """Assert this chunk is a verbatim slice of ``original``.

        Raises:
            ValueError: If the slice does not match, which means offsets are
                corrupt and nothing downstream can be trusted.
        """
        actual = original[self.start_offset : self.end_offset]
        if actual != self.text:
            raise ValueError(
                f"chunk {self.chunk_id} is not a verbatim slice of the note: "
                f"offsets [{self.start_offset}:{self.end_offset}] give "
                f"{len(actual)} chars but the chunk holds {len(self.text)}"
            )

to_original

to_original(local_offset: int) -> int

Map an offset inside this chunk to the original text.

Raises:

Type Description
ValueError

If the offset is outside the chunk, which would otherwise produce a plausible-looking but wrong global offset.

Source code in src/fhirground/preprocess/chunking.py
def to_original(self, local_offset: int) -> int:
    """Map an offset inside this chunk to the original text.

    Raises:
        ValueError: If the offset is outside the chunk, which would
            otherwise produce a plausible-looking but wrong global offset.
    """
    if not 0 <= local_offset <= len(self.text):
        raise ValueError(
            f"local offset {local_offset} is outside chunk {self.chunk_id} "
            f"of length {len(self.text)}"
        )
    return self.start_offset + local_offset

verify_against

verify_against(original: str) -> None

Assert this chunk is a verbatim slice of original.

Raises:

Type Description
ValueError

If the slice does not match, which means offsets are corrupt and nothing downstream can be trusted.

Source code in src/fhirground/preprocess/chunking.py
def verify_against(self, original: str) -> None:
    """Assert this chunk is a verbatim slice of ``original``.

    Raises:
        ValueError: If the slice does not match, which means offsets are
            corrupt and nothing downstream can be trusted.
    """
    actual = original[self.start_offset : self.end_offset]
    if actual != self.text:
        raise ValueError(
            f"chunk {self.chunk_id} is not a verbatim slice of the note: "
            f"offsets [{self.start_offset}:{self.end_offset}] give "
            f"{len(actual)} chars but the chunk holds {len(self.text)}"
        )

ChunkPlan dataclass

The chunks for one note, plus the sections they were cut against.

Source code in src/fhirground/preprocess/chunking.py
@dataclass
class ChunkPlan:
    """The chunks for one note, plus the sections they were cut against."""

    chunks: list[Chunk] = field(default_factory=list)
    sections: list[Section] = field(default_factory=list)

    def __len__(self) -> int:
        return len(self.chunks)

    def __iter__(self):
        return iter(self.chunks)

    def coverage(self, text_length: int) -> float:
        """Fraction of the note covered by at least one chunk.

        Should be 1.0. Anything less means text was dropped, which would make
        a finding unextractable for a reason nobody would notice.
        """
        if text_length == 0:
            return 1.0
        covered = bytearray(text_length)
        for chunk in self.chunks:
            for i in range(chunk.start_offset, min(chunk.end_offset, text_length)):
                covered[i] = 1
        return sum(covered) / text_length

coverage

coverage(text_length: int) -> float

Fraction of the note covered by at least one chunk.

Should be 1.0. Anything less means text was dropped, which would make a finding unextractable for a reason nobody would notice.

Source code in src/fhirground/preprocess/chunking.py
def coverage(self, text_length: int) -> float:
    """Fraction of the note covered by at least one chunk.

    Should be 1.0. Anything less means text was dropped, which would make
    a finding unextractable for a reason nobody would notice.
    """
    if text_length == 0:
        return 1.0
    covered = bytearray(text_length)
    for chunk in self.chunks:
        for i in range(chunk.start_offset, min(chunk.end_offset, text_length)):
            covered[i] = 1
    return sum(covered) / text_length

chunk_note

chunk_note(
    text: str,
    note_id: str,
    *,
    max_chars: int = 2000,
    overlap_chars: int = 200,
    section_headers: tuple[str, ...] | None = None,
    respect_sections: bool = True,
) -> ChunkPlan

Split a note into overlapping, offset-tracked chunks.

Overlap matters for recall: a finding whose sentence straddles a boundary would otherwise be invisible to both chunks. The cost is that the same mention may be extracted twice, which :mod:fhirground.dedup merges.

Parameters:

Name Type Description Default
text str

The original note text, used verbatim.

required
note_id str

Used to build chunk ids.

required
max_chars int

Maximum chunk length. Chunks may be shorter when a sentence boundary or a section edge falls earlier.

2000
overlap_chars int

How far each chunk reaches back into the previous one.

200
section_headers tuple[str, ...] | None

Header list for section detection.

None
respect_sections bool

When true, chunks do not span a section boundary, so a mention's section is unambiguous.

True

Returns:

Name Type Description
A ChunkPlan

class:ChunkPlan whose chunks tile the note with overlap.

Raises:

Type Description
ConfigError

If the chunk parameters cannot make progress.

Source code in src/fhirground/preprocess/chunking.py
def chunk_note(
    text: str,
    note_id: str,
    *,
    max_chars: int = 2000,
    overlap_chars: int = 200,
    section_headers: tuple[str, ...] | None = None,
    respect_sections: bool = True,
) -> ChunkPlan:
    """Split a note into overlapping, offset-tracked chunks.

    Overlap matters for recall: a finding whose sentence straddles a boundary
    would otherwise be invisible to both chunks. The cost is that the same
    mention may be extracted twice, which :mod:`fhirground.dedup` merges.

    Args:
        text: The original note text, used verbatim.
        note_id: Used to build chunk ids.
        max_chars: Maximum chunk length. Chunks may be shorter when a sentence
            boundary or a section edge falls earlier.
        overlap_chars: How far each chunk reaches back into the previous one.
        section_headers: Header list for section detection.
        respect_sections: When true, chunks do not span a section boundary, so
            a mention's section is unambiguous.

    Returns:
        A :class:`ChunkPlan` whose chunks tile the note with overlap.

    Raises:
        ConfigError: If the chunk parameters cannot make progress.
    """
    if max_chars < 50:
        raise ConfigError(f"max_chars must be at least 50, got {max_chars}")
    if overlap_chars < 0:
        raise ConfigError(f"overlap_chars must be non-negative, got {overlap_chars}")
    if overlap_chars >= max_chars:
        raise ConfigError(
            f"overlap_chars ({overlap_chars}) must be smaller than max_chars "
            f"({max_chars}), or chunking cannot advance"
        )

    sections = detect_sections(text, section_headers) if section_headers else detect_sections(text)
    if not text:
        return ChunkPlan(chunks=[], sections=sections)

    # Hard edges the chunker will not cross when respecting sections.
    edges: list[int] = [len(text)]
    if respect_sections and sections:
        edges = sorted({s.header_start for s in sections if s.header_start > 0} | {len(text)})

    chunks: list[Chunk] = []
    cursor = 0
    min_chars = max(1, min(max_chars // 4, 200))

    while cursor < len(text):
        next_edge = next((e for e in edges if e > cursor), len(text))
        hard_end = min(cursor + max_chars, next_edge)
        end = _choose_split(text, cursor, hard_end, min_chars)
        if end <= cursor:  # pragma: no cover - guarded by the parameter checks
            end = min(cursor + max_chars, len(text))

        chunks.append(
            Chunk(
                chunk_id=f"{note_id}#{len(chunks)}",
                index=len(chunks),
                text=text[cursor:end],
                start_offset=cursor,
                end_offset=end,
                section=section_at(sections, cursor),
            )
        )

        if end >= len(text):
            break
        # Step forward, then reach back by the overlap -- but never behind the
        # start of the chunk just emitted, or chunking would not terminate.
        cursor = max(cursor + 1, end - overlap_chars) if end < next_edge else end

    plan = ChunkPlan(chunks=chunks, sections=sections)
    for chunk in chunks:
        chunk.verify_against(text)
    return plan

Backends

fhirground.backends.base

The backend protocol.

A backend turns a prompt plus the mention schema into raw text. It does not parse, validate, repair, or know about FHIR -- :mod:fhirground.extract does that. Keeping the boundary there means a new backend is one small class, and the repair loop is tested once rather than per backend.

Backends must not log note text. RawResponse carries the text because the repair loop needs it, but every log line in this package records ids, counts, timings, and hashes only.

Backend

Bases: Protocol

Anything that can produce mention JSON from a prompt.

Source code in src/fhirground/backends/base.py
@runtime_checkable
class Backend(Protocol):
    """Anything that can produce mention JSON from a prompt."""

    name: str
    model_id: str

    def extract(
        self,
        prompt: str,
        schema: dict[str, Any],
        *,
        temperature: float = 0.0,
        n: int = 1,
    ) -> list[RawResponse]:
        """Produce ``n`` responses for ``prompt``, constrained to ``schema``.

        Args:
            prompt: The rendered prompt, including the chunk text.
            schema: The mention JSON Schema, as the constrained-decoding
                target.
            temperature: Sampling temperature. ``n > 1`` with temperature 0
                yields identical samples, so self-consistency needs a non-zero
                value to mean anything.
            n: Number of samples.

        Returns:
            One :class:`RawResponse` per sample.

        Raises:
            BackendError: On a transport, auth, or throttling failure. This is
                distinct from a schema failure, so it does not consume a
                repair attempt -- the model was never at fault.
        """
        ...

    def describe(self) -> dict[str, Any]:
        """Configuration summary for the run summary and Provenance."""
        ...

extract

extract(
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
) -> list[RawResponse]

Produce n responses for prompt, constrained to schema.

Parameters:

Name Type Description Default
prompt str

The rendered prompt, including the chunk text.

required
schema dict[str, Any]

The mention JSON Schema, as the constrained-decoding target.

required
temperature float

Sampling temperature. n > 1 with temperature 0 yields identical samples, so self-consistency needs a non-zero value to mean anything.

0.0
n int

Number of samples.

1

Returns:

Name Type Description
One list[RawResponse]

class:RawResponse per sample.

Raises:

Type Description
BackendError

On a transport, auth, or throttling failure. This is distinct from a schema failure, so it does not consume a repair attempt -- the model was never at fault.

Source code in src/fhirground/backends/base.py
def extract(
    self,
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
) -> list[RawResponse]:
    """Produce ``n`` responses for ``prompt``, constrained to ``schema``.

    Args:
        prompt: The rendered prompt, including the chunk text.
        schema: The mention JSON Schema, as the constrained-decoding
            target.
        temperature: Sampling temperature. ``n > 1`` with temperature 0
            yields identical samples, so self-consistency needs a non-zero
            value to mean anything.
        n: Number of samples.

    Returns:
        One :class:`RawResponse` per sample.

    Raises:
        BackendError: On a transport, auth, or throttling failure. This is
            distinct from a schema failure, so it does not consume a
            repair attempt -- the model was never at fault.
    """
    ...

describe

describe() -> dict[str, Any]

Configuration summary for the run summary and Provenance.

Source code in src/fhirground/backends/base.py
def describe(self) -> dict[str, Any]:
    """Configuration summary for the run summary and Provenance."""
    ...

RawResponse dataclass

One backend response, before parsing.

Attributes:

Name Type Description
text str

The raw response body, expected to be JSON matching the mention schema.

model_id str

Which model produced it.

tokens_in int | None

Prompt tokens, when the backend reports them.

tokens_out int | None

Completion tokens, when reported.

latency_s float | None

Wall-clock seconds for the call.

logprob float | None

Mean token probability, when the backend exposes it. Feeds the l confidence component, which is weighted 0 by default because few backends report it comparably.

finish_reason str | None

Backend-reported stop reason. length means the response was truncated, which is worth surfacing: truncated JSON fails to parse and consumes a repair attempt for a reason the model cannot fix.

cached bool

Whether this came from the on-disk cache rather than a call.

raw dict[str, Any]

The untouched provider payload, for debugging.

Source code in src/fhirground/backends/base.py
@dataclass
class RawResponse:
    """One backend response, before parsing.

    Attributes:
        text: The raw response body, expected to be JSON matching the mention
            schema.
        model_id: Which model produced it.
        tokens_in: Prompt tokens, when the backend reports them.
        tokens_out: Completion tokens, when reported.
        latency_s: Wall-clock seconds for the call.
        logprob: Mean token probability, when the backend exposes it. Feeds
            the ``l`` confidence component, which is weighted 0 by default
            because few backends report it comparably.
        finish_reason: Backend-reported stop reason. ``length`` means the
            response was truncated, which is worth surfacing: truncated JSON
            fails to parse and consumes a repair attempt for a reason the
            model cannot fix.
        cached: Whether this came from the on-disk cache rather than a call.
        raw: The untouched provider payload, for debugging.
    """

    text: str
    model_id: str = ""
    tokens_in: int | None = None
    tokens_out: int | None = None
    latency_s: float | None = None
    logprob: float | None = None
    finish_reason: str | None = None
    cached: bool = False
    raw: dict[str, Any] = field(default_factory=dict)

    @property
    def truncated(self) -> bool:
        """Whether the backend said it ran out of room."""
        return (self.finish_reason or "").lower() in ("length", "max_tokens")

truncated property

truncated: bool

Whether the backend said it ran out of room.

fhirground.backends.mock

The mock backend: deterministic, offline, fixture-driven.

Used by every unit test and by the bundled demo, which is how the whole pipeline runs in CI with no network and no API key. It is not a toy: the demo's end-to-end guarantee depends on it behaving exactly like a real backend from extract() outward.

Two modes:

  • fixtures -- a mapping from chunk text (or a hash of it) to the mention JSON a model returned. Recorded responses, replayed exactly.
  • rules -- a small deterministic extractor over the note text, so a freshly generated synthetic note produces sensible mentions without anyone hand-writing a fixture for it.

The rule mode is deliberately simple-minded and makes the same mistakes a weak model makes, which keeps the drop counters and confidence components exercised rather than always perfect.

MockBackend

A deterministic backend for tests, demos, and offline runs.

Parameters:

Name Type Description Default
fixtures dict[str, Any] | None

Chunk text (or its hash) -> mention JSON. Checked first.

None
rules bool

Fall back to the rule extractor when no fixture matches. With both off, an unmatched chunk returns no mentions.

True
model_id str

Recorded in Provenance.

'mock-deterministic-v1'
latency_s float

Simulated latency, reported but not slept.

0.0
fail_first_n int

Return malformed JSON for the first N calls, to exercise the repair loop deterministically.

0
malformed_payload str

What to return while failing.

'{"mentions": ['
Source code in src/fhirground/backends/mock.py
class MockBackend:
    """A deterministic backend for tests, demos, and offline runs.

    Args:
        fixtures: Chunk text (or its hash) -> mention JSON. Checked first.
        rules: Fall back to the rule extractor when no fixture matches. With
            both off, an unmatched chunk returns no mentions.
        model_id: Recorded in Provenance.
        latency_s: Simulated latency, reported but not slept.
        fail_first_n: Return malformed JSON for the first N calls, to exercise
            the repair loop deterministically.
        malformed_payload: What to return while failing.
    """

    name = "mock"

    def __init__(
        self,
        fixtures: dict[str, Any] | None = None,
        *,
        rules: bool = True,
        model_id: str = "mock-deterministic-v1",
        latency_s: float = 0.0,
        fail_first_n: int = 0,
        malformed_payload: str = '{"mentions": [',
    ) -> None:
        self.fixtures = dict(fixtures or {})
        self.rules = rules
        self.model_id = model_id
        self.latency_s = latency_s
        self.fail_first_n = fail_first_n
        self.malformed_payload = malformed_payload
        self.calls = 0

    # -- construction ---------------------------------------------------

    @classmethod
    def from_fixture_file(cls, path: str | Path, **kwargs: Any) -> MockBackend:
        """Load fixtures from a JSON object mapping chunk text to mention JSON."""
        source = Path(path)
        if not source.exists():
            raise BackendError(f"mock fixture file not found: {source}")
        try:
            data = json.loads(source.read_text(encoding="utf-8"))
        except json.JSONDecodeError as exc:
            raise BackendError(f"{source}: malformed JSON: {exc.msg}") from exc
        if not isinstance(data, dict):
            raise BackendError(f"{source}: expected a JSON object of chunk -> mentions")
        return cls(fixtures=data, **kwargs)

    @staticmethod
    def fixture_key(text: str) -> str:
        """Stable key for a chunk, so fixtures need not embed note text."""
        return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]

    # -- the Backend protocol -------------------------------------------

    def extract(
        self,
        prompt: str,
        schema: dict[str, Any],
        *,
        temperature: float = 0.0,
        n: int = 1,
    ) -> list[RawResponse]:
        """Return ``n`` deterministic responses.

        Samples are identical regardless of temperature: a mock that varied
        would make tests flaky, and self-consistency is tested directly in
        :mod:`fhirground.dedup` instead.
        """
        _ = schema, temperature
        self.calls += 1

        if self.calls <= self.fail_first_n:
            return [
                RawResponse(
                    text=self.malformed_payload,
                    model_id=self.model_id,
                    latency_s=self.latency_s,
                    finish_reason="stop",
                )
                for _ in range(max(1, n))
            ]

        chunk = _chunk_from_prompt(prompt)
        payload = self._lookup(chunk)
        text = json.dumps(payload)
        return [
            RawResponse(
                text=text,
                model_id=self.model_id,
                tokens_in=len(prompt) // 4,
                tokens_out=len(text) // 4,
                latency_s=self.latency_s,
                finish_reason="stop",
            )
            for _ in range(max(1, n))
        ]

    def describe(self) -> dict[str, Any]:
        """Configuration summary."""
        return {
            "backend": self.name,
            "model_id": self.model_id,
            "n_fixtures": len(self.fixtures),
            "rules": self.rules,
        }

    def _lookup(self, chunk: str) -> dict[str, Any]:
        """Fixture first, then rules, then nothing."""
        if chunk in self.fixtures:
            return _as_payload(self.fixtures[chunk])
        key = self.fixture_key(chunk)
        if key in self.fixtures:
            return _as_payload(self.fixtures[key])
        normalized = " ".join(chunk.split())
        if normalized in self.fixtures:
            return _as_payload(self.fixtures[normalized])
        if self.rules:
            return {"mentions": extract_by_rules(chunk)}
        return {"mentions": []}

from_fixture_file classmethod

from_fixture_file(
    path: str | Path, **kwargs: Any
) -> MockBackend

Load fixtures from a JSON object mapping chunk text to mention JSON.

Source code in src/fhirground/backends/mock.py
@classmethod
def from_fixture_file(cls, path: str | Path, **kwargs: Any) -> MockBackend:
    """Load fixtures from a JSON object mapping chunk text to mention JSON."""
    source = Path(path)
    if not source.exists():
        raise BackendError(f"mock fixture file not found: {source}")
    try:
        data = json.loads(source.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise BackendError(f"{source}: malformed JSON: {exc.msg}") from exc
    if not isinstance(data, dict):
        raise BackendError(f"{source}: expected a JSON object of chunk -> mentions")
    return cls(fixtures=data, **kwargs)

fixture_key staticmethod

fixture_key(text: str) -> str

Stable key for a chunk, so fixtures need not embed note text.

Source code in src/fhirground/backends/mock.py
@staticmethod
def fixture_key(text: str) -> str:
    """Stable key for a chunk, so fixtures need not embed note text."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]

extract

extract(
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
) -> list[RawResponse]

Return n deterministic responses.

Samples are identical regardless of temperature: a mock that varied would make tests flaky, and self-consistency is tested directly in :mod:fhirground.dedup instead.

Source code in src/fhirground/backends/mock.py
def extract(
    self,
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
) -> list[RawResponse]:
    """Return ``n`` deterministic responses.

    Samples are identical regardless of temperature: a mock that varied
    would make tests flaky, and self-consistency is tested directly in
    :mod:`fhirground.dedup` instead.
    """
    _ = schema, temperature
    self.calls += 1

    if self.calls <= self.fail_first_n:
        return [
            RawResponse(
                text=self.malformed_payload,
                model_id=self.model_id,
                latency_s=self.latency_s,
                finish_reason="stop",
            )
            for _ in range(max(1, n))
        ]

    chunk = _chunk_from_prompt(prompt)
    payload = self._lookup(chunk)
    text = json.dumps(payload)
    return [
        RawResponse(
            text=text,
            model_id=self.model_id,
            tokens_in=len(prompt) // 4,
            tokens_out=len(text) // 4,
            latency_s=self.latency_s,
            finish_reason="stop",
        )
        for _ in range(max(1, n))
    ]

describe

describe() -> dict[str, Any]

Configuration summary.

Source code in src/fhirground/backends/mock.py
def describe(self) -> dict[str, Any]:
    """Configuration summary."""
    return {
        "backend": self.name,
        "model_id": self.model_id,
        "n_fixtures": len(self.fixtures),
        "rules": self.rules,
    }

extract_by_rules

extract_by_rules(text: str) -> list[dict[str, Any]]

A deterministic, deliberately naive extractor over note text.

Produces the mention shapes a weak model produces, including the mistakes: it reads cues sentence-wide, so a sentence containing both a negation and a second finding mislabels the second one. That is on purpose -- it keeps the assertion policy and the drop counters exercised by the demo rather than always seeing clean input.

Source code in src/fhirground/backends/mock.py
def extract_by_rules(text: str) -> list[dict[str, Any]]:
    """A deterministic, deliberately naive extractor over note text.

    Produces the mention shapes a weak model produces, including the mistakes:
    it reads cues sentence-wide, so a sentence containing both a negation and a
    second finding mislabels the second one. That is on purpose -- it keeps the
    assertion policy and the drop counters exercised by the demo rather than
    always seeing clean input.
    """
    mentions: list[dict[str, Any]] = []
    seen: set[tuple[str, str, str]] = set()

    for sentence, _offset in _sentences(text):
        lowered = sentence.lower()
        assertion = _assertion_for(sentence)
        evidence = sentence.strip()
        if not evidence:
            continue

        for phrase in _CONDITIONS:
            if phrase in lowered:
                key = ("condition", phrase, assertion)
                if key in seen:
                    continue
                seen.add(key)
                mention: dict[str, Any] = {
                    "mention_type": "condition",
                    "text": phrase,
                    "evidence": evidence[:300],
                    "assertion": assertion,
                }
                if assertion == "historical":
                    mention["clinical_status_hint"] = "resolved"
                mentions.append(mention)
                break

        for phrase in _MEDICATIONS:
            if phrase in lowered:
                key = ("medication", phrase, assertion)
                if key in seen:
                    continue
                seen.add(key)
                mention = {
                    "mention_type": "medication",
                    "text": phrase,
                    "evidence": evidence[:300],
                    "assertion": assertion,
                    "med_action": _med_action_for(sentence),
                }
                dose = _DOSE.search(sentence)
                if dose:
                    mention["dose_value"] = float(dose.group("value"))
                    mention["dose_unit"] = dose.group("unit")
                route = _ROUTE.search(sentence)
                if route:
                    mention["route"] = route.group(1)
                freq = _FREQ.search(sentence)
                if freq:
                    mention["frequency_text"] = freq.group(1)
                mentions.append(mention)
                break

        for phrase, category in _OBSERVATIONS:
            if phrase not in lowered:
                continue
            key = ("observation", phrase, assertion)
            if key in seen:
                continue
            seen.add(key)
            mention = {
                "mention_type": "observation",
                "text": phrase,
                "evidence": evidence[:300],
                "assertion": assertion,
                "obs_category": category,
            }
            after = lowered.split(phrase, 1)[1] if phrase in lowered else ""
            value = _VALUE.search(after[:40])
            if value:
                mention["value_number"] = float(value.group("num"))
                if value.group("cmp"):
                    mention["value_comparator"] = value.group("cmp")
                if value.group("unit"):
                    mention["value_unit"] = value.group("unit")
            for cue in ("today", "yesterday"):
                if cue in lowered:
                    mention["date_text"] = cue
                    break
            mentions.append(mention)
            break

    return mentions

record_fixtures

record_fixtures(
    chunks: list[str], extractor: Any = None
) -> dict[str, list[dict[str, Any]]]

Build a fixture mapping from chunks, for checking in.

Parameters:

Name Type Description Default
chunks list[str]

Chunk texts.

required
extractor Any

Callable returning mentions for a chunk. Defaults to the rule extractor.

None

Returns:

Type Description
dict[str, list[dict[str, Any]]]

Hash-keyed fixtures, so the file does not embed note text verbatim.

Source code in src/fhirground/backends/mock.py
def record_fixtures(chunks: list[str], extractor: Any = None) -> dict[str, list[dict[str, Any]]]:
    """Build a fixture mapping from chunks, for checking in.

    Args:
        chunks: Chunk texts.
        extractor: Callable returning mentions for a chunk. Defaults to the
            rule extractor.

    Returns:
        Hash-keyed fixtures, so the file does not embed note text verbatim.
    """
    fn = extractor or extract_by_rules
    _ = time  # kept for API symmetry with recorded live fixtures
    return {MockBackend.fixture_key(c): fn(c) for c in chunks}

fhirground.backends.openai_compatible

OpenAI-compatible backend, for vLLM and anything speaking the same API.

Request shape verified against the OpenAI client's own type definitions (openai.types.shared_params.response_format_json_schema) rather than from memory: response_format = {"type": "json_schema", "json_schema": {"name", "schema", "strict"}}. See docs/decisions.md D-003.

Two constraint mechanisms, because servers differ:

  • response_format: json_schema -- the OpenAI-compatible spelling, which recent vLLM supports and which gives true token-level constrained decoding when the server's guided backend is active.
  • guided_json -- vLLM's older extra-body parameter, kept as a fallback for servers that predate the former.

strict defaults to False. OpenAI's strict mode requires every property to appear in required, and the mention schema deliberately has four required fields and fourteen optional ones -- a model forced to emit every field invents values for the ones it cannot support. vLLM's guided decoding constrains to the schema without that requirement, so strict buys nothing here and costs correctness.

No test in this package calls a server; the request builder is tested with respx.

OpenAICompatible

Chat-completions backend for an OpenAI-compatible server.

Parameters:

Name Type Description Default
base_url str

Server base, e.g. http://localhost:8000/v1.

required
model str

Model id the server exposes.

required
api_key str | None

Bearer token. vLLM usually needs none.

None
temperature float

Default sampling temperature.

0.0
max_tokens int

Completion cap. Too low truncates the JSON and burns a repair attempt on something the model cannot fix, so the default is generous.

2048
constraint_mode str

json_schema (default), guided_json, or none for a server with no constrained decoding at all.

'json_schema'
strict bool

Value for json_schema.strict. Off by default; see the module docstring.

False
timeout float

Per-request timeout in seconds.

120.0
client Client | None

Inject an httpx.Client for testing.

None
extra_body dict[str, Any] | None

Additional request fields, merged last.

None
Source code in src/fhirground/backends/openai_compatible.py
class OpenAICompatible:
    """Chat-completions backend for an OpenAI-compatible server.

    Args:
        base_url: Server base, e.g. ``http://localhost:8000/v1``.
        model: Model id the server exposes.
        api_key: Bearer token. vLLM usually needs none.
        temperature: Default sampling temperature.
        max_tokens: Completion cap. Too low truncates the JSON and burns a
            repair attempt on something the model cannot fix, so the default is
            generous.
        constraint_mode: ``json_schema`` (default), ``guided_json``, or
            ``none`` for a server with no constrained decoding at all.
        strict: Value for ``json_schema.strict``. Off by default; see the
            module docstring.
        timeout: Per-request timeout in seconds.
        client: Inject an ``httpx.Client`` for testing.
        extra_body: Additional request fields, merged last.
    """

    name = "openai_compatible"

    def __init__(
        self,
        *,
        base_url: str,
        model: str,
        api_key: str | None = None,
        temperature: float = 0.0,
        max_tokens: int = 2048,
        constraint_mode: str = "json_schema",
        strict: bool = False,
        timeout: float = 120.0,
        client: httpx.Client | None = None,
        extra_body: dict[str, Any] | None = None,
    ) -> None:
        if constraint_mode not in CONSTRAINT_MODES:
            raise BackendError(
                f"unknown constraint_mode {constraint_mode!r}; use one of {list(CONSTRAINT_MODES)}"
            )
        self.base_url = base_url.rstrip("/")
        self.model = model
        self.model_id = model
        self.api_key = api_key
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.constraint_mode = constraint_mode
        self.strict = strict
        self.timeout = timeout
        self.extra_body = dict(extra_body or {})
        self._client = client
        self._owns_client = client is None

    # -- plumbing -------------------------------------------------------

    def _get_client(self) -> httpx.Client:
        if self._client is None:
            self._client = httpx.Client(timeout=self.timeout)
        return self._client

    def close(self) -> None:
        """Close the HTTP client if this backend created it."""
        if self._client is not None and self._owns_client:
            self._client.close()
            self._client = None

    def __enter__(self) -> OpenAICompatible:
        return self

    def __exit__(self, *exc: object) -> None:
        self.close()

    def _headers(self) -> dict[str, str]:
        headers = {"Content-Type": "application/json"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        return headers

    # -- the request builder (unit-tested directly) ---------------------

    def build_request(
        self,
        prompt: str,
        schema: dict[str, Any],
        *,
        temperature: float | None = None,
        n: int = 1,
        system: str | None = None,
    ) -> dict[str, Any]:
        """Build the chat-completions request body.

        Separated from the call so SPEC §0's requirement -- a test that the
        mention schema is accepted by each backend's request builder -- can be
        met without a server.
        """
        messages: list[dict[str, str]] = []
        if system:
            messages.append({"role": "system", "content": system})
        messages.append({"role": "user", "content": prompt})

        body: dict[str, Any] = {
            "model": self.model,
            "messages": messages,
            "temperature": self.temperature if temperature is None else temperature,
            "max_tokens": self.max_tokens,
        }
        if n > 1:
            body["n"] = n

        if self.constraint_mode == "json_schema":
            body["response_format"] = {
                "type": "json_schema",
                "json_schema": {
                    "name": schema.get("title") or "MentionList",
                    "schema": schema,
                    "strict": self.strict,
                },
            }
        elif self.constraint_mode == "guided_json":
            # vLLM's extra-body form, for servers predating response_format.
            body["guided_json"] = schema
            body["guided_decoding_backend"] = self.extra_body.pop(
                "guided_decoding_backend", "outlines"
            )

        body.update(self.extra_body)
        return body

    # -- the Backend protocol -------------------------------------------

    def extract(
        self,
        prompt: str,
        schema: dict[str, Any],
        *,
        temperature: float = 0.0,
        n: int = 1,
        system: str | None = None,
    ) -> list[RawResponse]:
        """Call the server and return one response per sample."""
        body = self.build_request(prompt, schema, temperature=temperature, n=n, system=system)
        url = f"{self.base_url}/chat/completions"

        started = time.perf_counter()
        try:
            response = self._get_client().post(url, json=body, headers=self._headers())
        except httpx.HTTPError as exc:
            raise BackendError(
                f"request to {url} failed: {type(exc).__name__}. Is the server running?"
            ) from exc
        elapsed = time.perf_counter() - started

        if response.status_code == 401:
            raise BackendError(f"{url} rejected the credentials (401)")
        if response.status_code == 404:
            raise BackendError(
                f"{url} returned 404. Check --base-url includes the API prefix, usually '/v1'."
            )
        if response.status_code >= 400:
            raise BackendError(f"{url} returned {response.status_code}: {response.text[:300]}")

        try:
            payload = response.json()
        except json.JSONDecodeError as exc:
            raise BackendError(f"{url} returned a non-JSON body: {exc.msg}") from exc

        choices = payload.get("choices") or []
        if not choices:
            raise BackendError(f"{url} returned no choices")

        usage = payload.get("usage") or {}
        model_id = str(payload.get("model") or self.model)
        out: list[RawResponse] = []
        for choice in choices:
            message = choice.get("message") or {}
            out.append(
                RawResponse(
                    text=str(message.get("content") or ""),
                    model_id=model_id,
                    tokens_in=usage.get("prompt_tokens"),
                    tokens_out=usage.get("completion_tokens"),
                    latency_s=round(elapsed, 4),
                    logprob=_mean_logprob(choice),
                    finish_reason=choice.get("finish_reason"),
                    raw=choice,
                )
            )
        return out

    def describe(self) -> dict[str, Any]:
        """Configuration summary."""
        return {
            "backend": self.name,
            "base_url": self.base_url,
            "model_id": self.model_id,
            "constraint_mode": self.constraint_mode,
            "strict": self.strict,
            "temperature": self.temperature,
            "max_tokens": self.max_tokens,
        }

close

close() -> None

Close the HTTP client if this backend created it.

Source code in src/fhirground/backends/openai_compatible.py
def close(self) -> None:
    """Close the HTTP client if this backend created it."""
    if self._client is not None and self._owns_client:
        self._client.close()
        self._client = None

build_request

build_request(
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float | None = None,
    n: int = 1,
    system: str | None = None,
) -> dict[str, Any]

Build the chat-completions request body.

Separated from the call so SPEC §0's requirement -- a test that the mention schema is accepted by each backend's request builder -- can be met without a server.

Source code in src/fhirground/backends/openai_compatible.py
def build_request(
    self,
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float | None = None,
    n: int = 1,
    system: str | None = None,
) -> dict[str, Any]:
    """Build the chat-completions request body.

    Separated from the call so SPEC §0's requirement -- a test that the
    mention schema is accepted by each backend's request builder -- can be
    met without a server.
    """
    messages: list[dict[str, str]] = []
    if system:
        messages.append({"role": "system", "content": system})
    messages.append({"role": "user", "content": prompt})

    body: dict[str, Any] = {
        "model": self.model,
        "messages": messages,
        "temperature": self.temperature if temperature is None else temperature,
        "max_tokens": self.max_tokens,
    }
    if n > 1:
        body["n"] = n

    if self.constraint_mode == "json_schema":
        body["response_format"] = {
            "type": "json_schema",
            "json_schema": {
                "name": schema.get("title") or "MentionList",
                "schema": schema,
                "strict": self.strict,
            },
        }
    elif self.constraint_mode == "guided_json":
        # vLLM's extra-body form, for servers predating response_format.
        body["guided_json"] = schema
        body["guided_decoding_backend"] = self.extra_body.pop(
            "guided_decoding_backend", "outlines"
        )

    body.update(self.extra_body)
    return body

extract

extract(
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
    system: str | None = None,
) -> list[RawResponse]

Call the server and return one response per sample.

Source code in src/fhirground/backends/openai_compatible.py
def extract(
    self,
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
    system: str | None = None,
) -> list[RawResponse]:
    """Call the server and return one response per sample."""
    body = self.build_request(prompt, schema, temperature=temperature, n=n, system=system)
    url = f"{self.base_url}/chat/completions"

    started = time.perf_counter()
    try:
        response = self._get_client().post(url, json=body, headers=self._headers())
    except httpx.HTTPError as exc:
        raise BackendError(
            f"request to {url} failed: {type(exc).__name__}. Is the server running?"
        ) from exc
    elapsed = time.perf_counter() - started

    if response.status_code == 401:
        raise BackendError(f"{url} rejected the credentials (401)")
    if response.status_code == 404:
        raise BackendError(
            f"{url} returned 404. Check --base-url includes the API prefix, usually '/v1'."
        )
    if response.status_code >= 400:
        raise BackendError(f"{url} returned {response.status_code}: {response.text[:300]}")

    try:
        payload = response.json()
    except json.JSONDecodeError as exc:
        raise BackendError(f"{url} returned a non-JSON body: {exc.msg}") from exc

    choices = payload.get("choices") or []
    if not choices:
        raise BackendError(f"{url} returned no choices")

    usage = payload.get("usage") or {}
    model_id = str(payload.get("model") or self.model)
    out: list[RawResponse] = []
    for choice in choices:
        message = choice.get("message") or {}
        out.append(
            RawResponse(
                text=str(message.get("content") or ""),
                model_id=model_id,
                tokens_in=usage.get("prompt_tokens"),
                tokens_out=usage.get("completion_tokens"),
                latency_s=round(elapsed, 4),
                logprob=_mean_logprob(choice),
                finish_reason=choice.get("finish_reason"),
                raw=choice,
            )
        )
    return out

describe

describe() -> dict[str, Any]

Configuration summary.

Source code in src/fhirground/backends/openai_compatible.py
def describe(self) -> dict[str, Any]:
    """Configuration summary."""
    return {
        "backend": self.name,
        "base_url": self.base_url,
        "model_id": self.model_id,
        "constraint_mode": self.constraint_mode,
        "strict": self.strict,
        "temperature": self.temperature,
        "max_tokens": self.max_tokens,
    }

fhirground.backends.bedrock

Bedrock backend, using the Converse API with a single forced tool.

Request shape verified against botocore's own service model for bedrock-runtime rather than from documentation or memory (docs/decisions.md D-003):

  • Converse accepts toolConfig with tools (required) and toolChoice;
  • toolSpec requires name and inputSchema, and also offers description and strict;
  • inputSchema is a union whose only member is json, a free-form document -- so the mention schema goes in as-is;
  • toolChoice supports any, auto, and tool: {name}.

Converse has no response_format-style structured output, so the forced-tool approach is the right one: one tool, toolChoice.tool, and the model's arguments are the mention JSON.

boto3 is an optional extra. Credentials come from the standard boto3 chain, never from fhirground configuration -- this package should not be in the business of holding AWS keys.

BedrockBackend

Converse-API backend with a forced tool carrying the mention schema.

Parameters:

Name Type Description Default
model_id str

Bedrock model id or inference profile ARN.

required
region str

AWS region.

'us-east-1'
temperature float

Default sampling temperature.

0.0
max_tokens int

Completion cap.

2048
client Any

Inject a bedrock-runtime client for testing. Tests use botocore's Stubber, so no test here reaches AWS.

None
strict bool

Value for toolSpec.strict, when the service supports it. Off by default for the same reason as the OpenAI backend: the mention schema has mostly-optional fields on purpose.

False
additional_model_request_fields dict[str, Any] | None

Passed through to Converse for model-specific options.

None
Source code in src/fhirground/backends/bedrock.py
class BedrockBackend:
    """Converse-API backend with a forced tool carrying the mention schema.

    Args:
        model_id: Bedrock model id or inference profile ARN.
        region: AWS region.
        temperature: Default sampling temperature.
        max_tokens: Completion cap.
        client: Inject a ``bedrock-runtime`` client for testing. Tests use
            botocore's ``Stubber``, so no test here reaches AWS.
        strict: Value for ``toolSpec.strict``, when the service supports it.
            Off by default for the same reason as the OpenAI backend: the
            mention schema has mostly-optional fields on purpose.
        additional_model_request_fields: Passed through to Converse for
            model-specific options.
    """

    name = "bedrock"

    def __init__(
        self,
        *,
        model_id: str,
        region: str = "us-east-1",
        temperature: float = 0.0,
        max_tokens: int = 2048,
        client: Any = None,
        strict: bool = False,
        additional_model_request_fields: dict[str, Any] | None = None,
    ) -> None:
        self.model_id = model_id
        self.region = region
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.strict = strict
        self.additional_model_request_fields = dict(additional_model_request_fields or {})
        self._client = client

    def _get_client(self) -> Any:
        if self._client is None:
            try:
                import boto3
            except ImportError as exc:
                raise BackendError(
                    "the Bedrock backend needs the optional extra: "
                    "pip install 'fhirground[bedrock]'"
                ) from exc
            self._client = boto3.client("bedrock-runtime", region_name=self.region)
        return self._client

    # -- the request builder (unit-tested with Stubber) -----------------

    def build_request(
        self,
        prompt: str,
        schema: dict[str, Any],
        *,
        temperature: float | None = None,
        system: str | None = None,
    ) -> dict[str, Any]:
        """Build the ``Converse`` request keyword arguments.

        The mention schema goes into ``toolConfig.tools[0].toolSpec.inputSchema.json``
        unchanged, and ``toolChoice`` forces that one tool so the model cannot
        answer in prose.
        """
        tool_spec: dict[str, Any] = {
            "name": TOOL_NAME,
            "description": TOOL_DESCRIPTION,
            "inputSchema": {"json": schema},
        }
        if self.strict:
            tool_spec["strict"] = True

        request: dict[str, Any] = {
            "modelId": self.model_id,
            "messages": [{"role": "user", "content": [{"text": prompt}]}],
            "inferenceConfig": {
                "temperature": self.temperature if temperature is None else temperature,
                "maxTokens": self.max_tokens,
            },
            "toolConfig": {
                "tools": [{"toolSpec": tool_spec}],
                "toolChoice": {"tool": {"name": TOOL_NAME}},
            },
        }
        if system:
            request["system"] = [{"text": system}]
        if self.additional_model_request_fields:
            request["additionalModelRequestFields"] = self.additional_model_request_fields
        return request

    # -- the Backend protocol -------------------------------------------

    def extract(
        self,
        prompt: str,
        schema: dict[str, Any],
        *,
        temperature: float = 0.0,
        n: int = 1,
        system: str | None = None,
    ) -> list[RawResponse]:
        """Call Converse ``n`` times and return one response per call.

        Converse returns a single message per call, so ``n > 1`` means ``n``
        calls. That is the honest implementation: faking samples from one
        response would make the self-consistency component meaningless.
        """
        client = self._get_client()
        request = self.build_request(prompt, schema, temperature=temperature, system=system)

        out: list[RawResponse] = []
        for _ in range(max(1, n)):
            started = time.perf_counter()
            try:
                response = client.converse(**request)
            except Exception as exc:
                raise self._translate(exc) from exc
            elapsed = time.perf_counter() - started
            out.append(self._parse(response, elapsed))
        return out

    def _translate(self, exc: Exception) -> BackendError:
        """Turn a botocore error into a BackendError with a usable message."""
        code = ""
        response = getattr(exc, "response", None)
        if isinstance(response, dict):
            code = str((response.get("Error") or {}).get("Code") or "")

        if code in _AUTH_ERRORS:
            return BackendError(
                f"Bedrock rejected the credentials ({code}). Credentials come from the "
                "standard boto3 chain; check your profile, role, and region "
                f"({self.region})."
            )
        if code in _THROTTLE_ERRORS:
            return BackendError(
                f"Bedrock throttled the request ({code}). Lower --concurrency or request "
                "a quota increase."
            )
        if code == "ValidationException":
            return BackendError(
                f"Bedrock rejected the request ({code}): {exc}. If this names the tool "
                "schema, the mention schema has left the subset Bedrock accepts -- "
                "fhirground.schemas.assert_backend_safe checks for that."
            )
        if code == "ResourceNotFoundException":
            return BackendError(
                f"Bedrock has no model {self.model_id!r} in {self.region} ({code}). "
                "Check the model id and that access is enabled for your account."
            )
        return BackendError(f"Bedrock call failed: {type(exc).__name__}: {exc}")

    def _parse(self, response: dict[str, Any], elapsed: float) -> RawResponse:
        """Pull the tool input back out of a Converse response."""
        usage = response.get("usage") or {}
        output = response.get("output") or {}
        message = output.get("message") or {}
        blocks = message.get("content") or []

        tool_input: Any = None
        text_parts: list[str] = []
        for block in blocks:
            if not isinstance(block, dict):
                continue
            if "toolUse" in block:
                use = block["toolUse"] or {}
                if use.get("name") == TOOL_NAME:
                    tool_input = use.get("input")
            elif "text" in block:
                text_parts.append(str(block["text"]))

        if tool_input is not None:
            text = json.dumps(tool_input)
        elif text_parts:
            # The model answered in prose despite toolChoice. Pass it through so
            # the repair loop can tell it what was wrong, rather than raising a
            # backend error for something the model can fix.
            text = "\n".join(text_parts)
        else:
            text = ""

        return RawResponse(
            text=text,
            model_id=self.model_id,
            tokens_in=usage.get("inputTokens"),
            tokens_out=usage.get("outputTokens"),
            latency_s=round(elapsed, 4),
            finish_reason=response.get("stopReason"),
            raw={"stopReason": response.get("stopReason"), "usage": usage},
        )

    def describe(self) -> dict[str, Any]:
        """Configuration summary."""
        return {
            "backend": self.name,
            "model_id": self.model_id,
            "region": self.region,
            "tool_name": TOOL_NAME,
            "strict": self.strict,
            "temperature": self.temperature,
            "max_tokens": self.max_tokens,
        }

build_request

build_request(
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float | None = None,
    system: str | None = None,
) -> dict[str, Any]

Build the Converse request keyword arguments.

The mention schema goes into toolConfig.tools[0].toolSpec.inputSchema.json unchanged, and toolChoice forces that one tool so the model cannot answer in prose.

Source code in src/fhirground/backends/bedrock.py
def build_request(
    self,
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float | None = None,
    system: str | None = None,
) -> dict[str, Any]:
    """Build the ``Converse`` request keyword arguments.

    The mention schema goes into ``toolConfig.tools[0].toolSpec.inputSchema.json``
    unchanged, and ``toolChoice`` forces that one tool so the model cannot
    answer in prose.
    """
    tool_spec: dict[str, Any] = {
        "name": TOOL_NAME,
        "description": TOOL_DESCRIPTION,
        "inputSchema": {"json": schema},
    }
    if self.strict:
        tool_spec["strict"] = True

    request: dict[str, Any] = {
        "modelId": self.model_id,
        "messages": [{"role": "user", "content": [{"text": prompt}]}],
        "inferenceConfig": {
            "temperature": self.temperature if temperature is None else temperature,
            "maxTokens": self.max_tokens,
        },
        "toolConfig": {
            "tools": [{"toolSpec": tool_spec}],
            "toolChoice": {"tool": {"name": TOOL_NAME}},
        },
    }
    if system:
        request["system"] = [{"text": system}]
    if self.additional_model_request_fields:
        request["additionalModelRequestFields"] = self.additional_model_request_fields
    return request

extract

extract(
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
    system: str | None = None,
) -> list[RawResponse]

Call Converse n times and return one response per call.

Converse returns a single message per call, so n > 1 means n calls. That is the honest implementation: faking samples from one response would make the self-consistency component meaningless.

Source code in src/fhirground/backends/bedrock.py
def extract(
    self,
    prompt: str,
    schema: dict[str, Any],
    *,
    temperature: float = 0.0,
    n: int = 1,
    system: str | None = None,
) -> list[RawResponse]:
    """Call Converse ``n`` times and return one response per call.

    Converse returns a single message per call, so ``n > 1`` means ``n``
    calls. That is the honest implementation: faking samples from one
    response would make the self-consistency component meaningless.
    """
    client = self._get_client()
    request = self.build_request(prompt, schema, temperature=temperature, system=system)

    out: list[RawResponse] = []
    for _ in range(max(1, n)):
        started = time.perf_counter()
        try:
            response = client.converse(**request)
        except Exception as exc:
            raise self._translate(exc) from exc
        elapsed = time.perf_counter() - started
        out.append(self._parse(response, elapsed))
    return out

describe

describe() -> dict[str, Any]

Configuration summary.

Source code in src/fhirground/backends/bedrock.py
def describe(self) -> dict[str, Any]:
    """Configuration summary."""
    return {
        "backend": self.name,
        "model_id": self.model_id,
        "region": self.region,
        "tool_name": TOOL_NAME,
        "strict": self.strict,
        "temperature": self.temperature,
        "max_tokens": self.max_tokens,
    }

fhirground.backends.prompts

Versioned prompt templates.

The prompt_version string goes into every Provenance, so a result can be traced to the exact instructions that produced it. Changing a template without bumping the version makes two runs indistinguishable in the output while actually differing -- so the version is part of the template constant, not a parameter.

The prompt tells the model what not to do as explicitly as what to do, because the failure modes are predictable: inventing codes, paraphrasing the evidence quote, and reporting family history as the patient's own.

RenderedPrompt dataclass

A prompt ready for a backend.

Source code in src/fhirground/backends/prompts.py
@dataclass(frozen=True, slots=True)
class RenderedPrompt:
    """A prompt ready for a backend."""

    system: str
    user: str
    version: str = PROMPT_VERSION

    @property
    def combined(self) -> str:
        """System and user joined, for backends with no system-message slot."""
        return f"{self.system}\n\n{self.user}"

    def digest(self) -> str:
        """Short hash of the full prompt, for the LLM call cache key."""
        import hashlib

        return hashlib.sha256(self.combined.encode("utf-8")).hexdigest()[:16]

combined property

combined: str

System and user joined, for backends with no system-message slot.

digest

digest() -> str

Short hash of the full prompt, for the LLM call cache key.

Source code in src/fhirground/backends/prompts.py
def digest(self) -> str:
    """Short hash of the full prompt, for the LLM call cache key."""
    import hashlib

    return hashlib.sha256(self.combined.encode("utf-8")).hexdigest()[:16]

render

render(
    chunk_text: str,
    *,
    section: str | None = None,
    note_datetime: str | None = None,
) -> RenderedPrompt

Render the extraction prompt for one chunk.

Parameters:

Name Type Description Default
chunk_text str

The verbatim chunk.

required
section str | None

Section the chunk came from, supplied as context so the model can read a bare "hypertension" under Family History correctly.

None
note_datetime str | None

The note's timestamp, so relative phrases can be reported as written and resolved later by code.

None

Returns:

Name Type Description
A RenderedPrompt

class:RenderedPrompt.

Source code in src/fhirground/backends/prompts.py
def render(
    chunk_text: str,
    *,
    section: str | None = None,
    note_datetime: str | None = None,
) -> RenderedPrompt:
    """Render the extraction prompt for one chunk.

    Args:
        chunk_text: The verbatim chunk.
        section: Section the chunk came from, supplied as context so the model
            can read a bare "hypertension" under *Family History* correctly.
        note_datetime: The note's timestamp, so relative phrases can be
            reported as written and resolved later by code.

    Returns:
        A :class:`RenderedPrompt`.
    """
    lines: list[str] = []
    if section:
        lines.append(f"This text comes from the note's {section!r} section.")
    if note_datetime:
        lines.append(f"The note was written on {note_datetime}.")
    context = ("\n".join(lines) + "\n\n") if lines else ""
    return RenderedPrompt(system=_SYSTEM, user=_USER.format(context=context, chunk=chunk_text))

render_repair

render_repair(
    previous: RenderedPrompt, error: str
) -> RenderedPrompt

Render the repair prompt after a parse or schema failure.

The error text is fed back verbatim because it names the offending field and what was expected -- which is exactly what a model needs to fix it.

Source code in src/fhirground/backends/prompts.py
def render_repair(previous: RenderedPrompt, error: str) -> RenderedPrompt:
    """Render the repair prompt after a parse or schema failure.

    The error text is fed back verbatim because it names the offending field
    and what was expected -- which is exactly what a model needs to fix it.
    """
    return RenderedPrompt(
        system=previous.system,
        user=f"{previous.user}\n\n{_REPAIR.format(error=error)}",
        version=previous.version,
    )

Extraction and the repair loop

fhirground.extract

Chunk to mentions: the backend call, parsing, and the repair loop.

Three responsibilities, deliberately kept out of the backends:

  1. Parse the raw text as JSON and validate it against the mention model. Models wrap JSON in prose and markdown fences; this strips what can be stripped without guessing at content.
  2. Repair on failure, by re-prompting with the validation error. Capped at max_repairs (default 2), and the count feeds the v confidence component -- a mention that took two attempts is worth less than one that parsed first time.
  3. Cache calls on disk, keyed by backend config, prompt, and chunk.

A transport or auth failure is not a repair case: the model was never at fault, so :class:~fhirground.exceptions.BackendError propagates immediately rather than burning attempts.

The cache contains note text, because the prompt does. That is documented in the PHI page and the cache is easy to disable.

ChunkExtraction dataclass

What one chunk produced.

Attributes:

Name Type Description
chunk_id str

Which chunk.

mentions MentionList

The parsed mention list, empty when extraction failed.

samples list[MentionList]

Per-sample mention lists, when n > 1. Used for the self-consistency confidence component.

repairs int

Repair attempts consumed. Feeds the v component.

responses list[RawResponse]

The raw responses, for the debug trace.

error str | None

The final error when every attempt failed.

cached bool

Whether the first response came from cache.

Source code in src/fhirground/extract.py
@dataclass
class ChunkExtraction:
    """What one chunk produced.

    Attributes:
        chunk_id: Which chunk.
        mentions: The parsed mention list, empty when extraction failed.
        samples: Per-sample mention lists, when ``n > 1``. Used for the
            self-consistency confidence component.
        repairs: Repair attempts consumed. Feeds the ``v`` component.
        responses: The raw responses, for the debug trace.
        error: The final error when every attempt failed.
        cached: Whether the first response came from cache.
    """

    chunk_id: str
    mentions: MentionList = field(default_factory=MentionList)
    samples: list[MentionList] = field(default_factory=list)
    repairs: int = 0
    responses: list[RawResponse] = field(default_factory=list)
    error: str | None = None
    cached: bool = False

    @property
    def ok(self) -> bool:
        """Whether a mention list was recovered."""
        return self.error is None

    @property
    def tokens_in(self) -> int:
        """Prompt tokens across every attempt."""
        return sum(r.tokens_in or 0 for r in self.responses)

    @property
    def tokens_out(self) -> int:
        """Completion tokens across every attempt."""
        return sum(r.tokens_out or 0 for r in self.responses)

    @property
    def latency_s(self) -> float:
        """Summed wall-clock across every attempt."""
        return sum(r.latency_s or 0.0 for r in self.responses)

ok property

ok: bool

Whether a mention list was recovered.

tokens_in property

tokens_in: int

Prompt tokens across every attempt.

tokens_out property

tokens_out: int

Completion tokens across every attempt.

latency_s property

latency_s: float

Summed wall-clock across every attempt.

CallCache

SQLite cache of backend calls.

Keyed by a hash of backend description, prompt, temperature, and sample count, so changing any of them is a cache miss rather than a stale hit.

The cached value includes the prompt, which includes note text. The PHI documentation says so, and PipelineConfig.cache_path=None disables it.

Source code in src/fhirground/extract.py
class CallCache:
    """SQLite cache of backend calls.

    Keyed by a hash of backend description, prompt, temperature, and sample
    count, so changing any of them is a cache miss rather than a stale hit.

    The cached value includes the prompt, which includes **note text**. The PHI
    documentation says so, and ``PipelineConfig.cache_path=None`` disables it.
    """

    def __init__(self, path: str | Path) -> None:
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self._lock = threading.Lock()
        self.hits = 0
        self.misses = 0
        with self._connect() as conn:
            conn.execute(
                "CREATE TABLE IF NOT EXISTS llm_cache ("
                " key TEXT PRIMARY KEY, payload TEXT NOT NULL,"
                " created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)"
            )

    def _connect(self) -> sqlite3.Connection:
        return sqlite3.connect(self.path, timeout=15.0)

    @staticmethod
    def make_key(
        backend_description: dict[str, Any],
        prompt: str,
        *,
        temperature: float,
        n: int,
        schema_digest: str,
    ) -> str:
        """Hash the inputs that determine a response."""
        blob = json.dumps(
            {
                "backend": backend_description,
                "prompt": prompt,
                "temperature": temperature,
                "n": n,
                "schema": schema_digest,
            },
            sort_keys=True,
        )
        return hashlib.sha256(blob.encode("utf-8")).hexdigest()

    def get(self, key: str) -> list[RawResponse] | None:
        """Look up cached responses."""
        with self._lock, self._connect() as conn:
            row = conn.execute("SELECT payload FROM llm_cache WHERE key = ?", (key,)).fetchone()
        if not row:
            self.misses += 1
            return None
        self.hits += 1
        return [RawResponse(**{**item, "cached": True}) for item in json.loads(row[0])]

    def put(self, key: str, responses: list[RawResponse]) -> None:
        """Store responses."""
        payload = json.dumps(
            [
                {
                    "text": r.text,
                    "model_id": r.model_id,
                    "tokens_in": r.tokens_in,
                    "tokens_out": r.tokens_out,
                    "latency_s": r.latency_s,
                    "logprob": r.logprob,
                    "finish_reason": r.finish_reason,
                }
                for r in responses
            ]
        )
        with self._lock, self._connect() as conn:
            conn.execute(
                "INSERT OR REPLACE INTO llm_cache (key, payload) VALUES (?, ?)",
                (key, payload),
            )

    def stats(self) -> dict[str, int]:
        """Hit and miss counts for the run summary."""
        return {"hits": self.hits, "misses": self.misses}

make_key staticmethod

make_key(
    backend_description: dict[str, Any],
    prompt: str,
    *,
    temperature: float,
    n: int,
    schema_digest: str,
) -> str

Hash the inputs that determine a response.

Source code in src/fhirground/extract.py
@staticmethod
def make_key(
    backend_description: dict[str, Any],
    prompt: str,
    *,
    temperature: float,
    n: int,
    schema_digest: str,
) -> str:
    """Hash the inputs that determine a response."""
    blob = json.dumps(
        {
            "backend": backend_description,
            "prompt": prompt,
            "temperature": temperature,
            "n": n,
            "schema": schema_digest,
        },
        sort_keys=True,
    )
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()

get

get(key: str) -> list[RawResponse] | None

Look up cached responses.

Source code in src/fhirground/extract.py
def get(self, key: str) -> list[RawResponse] | None:
    """Look up cached responses."""
    with self._lock, self._connect() as conn:
        row = conn.execute("SELECT payload FROM llm_cache WHERE key = ?", (key,)).fetchone()
    if not row:
        self.misses += 1
        return None
    self.hits += 1
    return [RawResponse(**{**item, "cached": True}) for item in json.loads(row[0])]

put

put(key: str, responses: list[RawResponse]) -> None

Store responses.

Source code in src/fhirground/extract.py
def put(self, key: str, responses: list[RawResponse]) -> None:
    """Store responses."""
    payload = json.dumps(
        [
            {
                "text": r.text,
                "model_id": r.model_id,
                "tokens_in": r.tokens_in,
                "tokens_out": r.tokens_out,
                "latency_s": r.latency_s,
                "logprob": r.logprob,
                "finish_reason": r.finish_reason,
            }
            for r in responses
        ]
    )
    with self._lock, self._connect() as conn:
        conn.execute(
            "INSERT OR REPLACE INTO llm_cache (key, payload) VALUES (?, ?)",
            (key, payload),
        )

stats

stats() -> dict[str, int]

Hit and miss counts for the run summary.

Source code in src/fhirground/extract.py
def stats(self) -> dict[str, int]:
    """Hit and miss counts for the run summary."""
    return {"hits": self.hits, "misses": self.misses}

extract_chunk

extract_chunk(
    chunk: Chunk,
    backend: Backend,
    schema: dict[str, Any],
    *,
    note_datetime: str | None = None,
    temperature: float = 0.0,
    samples: int = 1,
    max_repairs: int = 2,
    cache: CallCache | None = None,
    schema_digest: str = "",
) -> ChunkExtraction

Extract mentions from one chunk, repairing on schema failure.

Parameters:

Name Type Description Default
chunk Chunk

The chunk to extract from.

required
backend Backend

The backend to call.

required
schema dict[str, Any]

The mention JSON Schema.

required
note_datetime str | None

Passed to the prompt as context.

None
temperature float

Sampling temperature.

0.0
samples int

Number of samples. Above 1 with a non-zero temperature, the per-sample lists feed the self-consistency component.

1
max_repairs int

Attempts after the first failure.

2
cache CallCache | None

Optional on-disk cache.

None
schema_digest str

Short schema hash, part of the cache key.

''

Returns:

Name Type Description
A ChunkExtraction

class:ChunkExtraction. A chunk that never parsed comes back with

ChunkExtraction

error set and no mentions, rather than raising -- one bad chunk

ChunkExtraction

should not abandon the note.

Source code in src/fhirground/extract.py
def extract_chunk(
    chunk: Chunk,
    backend: Backend,
    schema: dict[str, Any],
    *,
    note_datetime: str | None = None,
    temperature: float = 0.0,
    samples: int = 1,
    max_repairs: int = 2,
    cache: CallCache | None = None,
    schema_digest: str = "",
) -> ChunkExtraction:
    """Extract mentions from one chunk, repairing on schema failure.

    Args:
        chunk: The chunk to extract from.
        backend: The backend to call.
        schema: The mention JSON Schema.
        note_datetime: Passed to the prompt as context.
        temperature: Sampling temperature.
        samples: Number of samples. Above 1 with a non-zero temperature, the
            per-sample lists feed the self-consistency component.
        max_repairs: Attempts after the first failure.
        cache: Optional on-disk cache.
        schema_digest: Short schema hash, part of the cache key.

    Returns:
        A :class:`ChunkExtraction`. A chunk that never parsed comes back with
        ``error`` set and no mentions, rather than raising -- one bad chunk
        should not abandon the note.
    """
    prompt = render(chunk.text, section=chunk.section, note_datetime=note_datetime)
    result = ChunkExtraction(chunk_id=chunk.chunk_id)
    current = prompt
    last_error: str | None = None

    for attempt in range(max_repairs + 1):
        responses = _call(
            backend,
            current,
            schema,
            temperature=temperature,
            n=samples,
            cache=cache,
            schema_digest=schema_digest,
        )
        result.responses.extend(responses)
        if attempt == 0 and responses and responses[0].cached:
            result.cached = True

        parsed: list[MentionList] = []
        error: str | None = None
        for response in responses:
            try:
                parsed.append(parse_mentions(response.text))
            except SchemaValidationError as exc:
                error = str(exc)
                if response.truncated:
                    error = (
                        f"{error}\n\nThe response was cut off at the token limit, so the "
                        "JSON was incomplete. Report fewer findings or shorter evidence "
                        "quotes."
                    )

        if parsed:
            result.mentions = parsed[0]
            result.samples = parsed
            result.repairs = attempt
            result.error = None
            return result

        last_error = error or "the response could not be parsed"
        result.repairs = attempt
        if attempt < max_repairs:
            current = render_repair(prompt, last_error)

    result.error = last_error
    return result

parse_mentions

parse_mentions(text: str) -> MentionList

Parse a raw response into a validated :class:MentionList.

Raises:

Type Description
SchemaValidationError

With a message written to be read by a model -- it names the offending field and what was expected, because that message is fed straight back in the repair prompt.

Source code in src/fhirground/extract.py
def parse_mentions(text: str) -> MentionList:
    """Parse a raw response into a validated :class:`MentionList`.

    Raises:
        SchemaValidationError: With a message written to be read *by a model*
            -- it names the offending field and what was expected, because
            that message is fed straight back in the repair prompt.
    """
    body = strip_to_json(text)
    if not body:
        raise SchemaValidationError(
            "The response was empty. Return a JSON object with a 'mentions' array.",
            raw_excerpt="",
        )

    try:
        data = json.loads(body)
    except json.JSONDecodeError as exc:
        raise SchemaValidationError(
            f"The response is not valid JSON: {exc.msg} at line {exc.lineno} "
            f"column {exc.colno}. Return a single JSON object and nothing else.",
            raw_excerpt=body[:200],
        ) from exc

    if isinstance(data, list):
        # A bare array is a common near-miss; accept it rather than spending a
        # repair attempt on a wrapper the model clearly intended.
        data = {"mentions": data}
    if not isinstance(data, dict):
        raise SchemaValidationError(
            f"The top level must be a JSON object with a 'mentions' array, but it was "
            f"a {type(data).__name__}.",
            raw_excerpt=body[:200],
        )

    try:
        return MentionList.model_validate(data)
    except ValidationError as exc:
        raise SchemaValidationError(_format_for_model(exc), raw_excerpt=body[:200]) from exc

strip_to_json

strip_to_json(text: str) -> str

Recover the JSON value from a response that may be wrapped.

Handles a markdown fence and leading or trailing prose. Objects and arrays are both recognized: looking only for {...} would reduce a bare [{...}, {...}] -- a common near-miss where the model omits the wrapper -- to just its first element, silently dropping every other mention.

Does not attempt to fix malformed JSON. Repairing syntax by guessing would change what the model said; the repair loop exists to ask it instead.

Source code in src/fhirground/extract.py
def strip_to_json(text: str) -> str:
    """Recover the JSON value from a response that may be wrapped.

    Handles a markdown fence and leading or trailing prose. Objects **and**
    arrays are both recognized: looking only for ``{...}`` would reduce a bare
    ``[{...}, {...}]`` -- a common near-miss where the model omits the wrapper
    -- to just its first element, silently dropping every other mention.

    Does **not** attempt to fix malformed JSON. Repairing syntax by guessing
    would change what the model said; the repair loop exists to ask it instead.
    """
    if not text:
        return ""
    fenced = _FENCE.search(text)
    if fenced:
        return fenced.group("body").strip()

    stripped = text.strip()
    candidates: list[tuple[int, int]] = []
    for opener, closer in (("{", "}"), ("[", "]")):
        start, end = stripped.find(opener), stripped.rfind(closer)
        if start >= 0 and end > start:
            candidates.append((start, end))
    if not candidates:
        return stripped
    # Whichever bracket opens first is the outer value.
    start, end = min(candidates, key=lambda pair: pair[0])
    return stripped[start : end + 1]

Grounding

fhirground.grounding

Grounding: locating a mention's evidence quote in the original note.

A mention whose evidence cannot be found in the note is dropped, not emitted with a guess. That is design principle 2, and it is the difference between an auditable extraction and a plausible one: every resource fhirground emits carries offsets that index the real note text, so a reviewer can always go read the sentence the claim came from.

Three strategies, tried in order, each with a lower confidence contribution:

  1. exact -- the quote appears verbatim. Score 1.0.
  2. normalized -- it appears once whitespace is collapsed and case folded. Models routinely re-space and re-capitalize what they "copied". Score 0.9.
  3. fuzzy -- rapidfuzz partial_ratio over a sliding window clears the threshold. Score ratio/100 * 0.8.

Below the threshold, the mention is dropped and counted.

Grounding dataclass

Where a mention's evidence sits in the original note.

Attributes:

Name Type Description
start int

Offset in the original note text, not the chunk.

end int

Exclusive end offset in the original text.

quote str

The text actually found at those offsets, which may differ from the model's quote under normalized or fuzzy matching. Storing what is really there, rather than what the model claimed, is what makes the offset/quote invariant checkable.

strategy GroundingStrategy

Which strategy succeeded.

score float

Grounding confidence component in [0, 1].

ambiguous bool

True when the quote occurs more than once in the chunk and the first occurrence was taken.

chunk_id str | None

The chunk the match was found in.

Source code in src/fhirground/grounding.py
@dataclass(frozen=True, slots=True)
class Grounding:
    """Where a mention's evidence sits in the original note.

    Attributes:
        start: Offset in the **original note text**, not the chunk.
        end: Exclusive end offset in the original text.
        quote: The text actually found at those offsets, which may differ from
            the model's quote under normalized or fuzzy matching. Storing what
            is really there, rather than what the model claimed, is what makes
            the offset/quote invariant checkable.
        strategy: Which strategy succeeded.
        score: Grounding confidence component in [0, 1].
        ambiguous: True when the quote occurs more than once in the chunk and
            the first occurrence was taken.
        chunk_id: The chunk the match was found in.
    """

    start: int
    end: int
    quote: str
    strategy: GroundingStrategy
    score: float
    ambiguous: bool = False
    chunk_id: str | None = None

    @property
    def length(self) -> int:
        """Character length of the grounded span."""
        return self.end - self.start

    def verify(self, original: str) -> bool:
        """Whether ``original[start:end]`` still equals the stored quote."""
        return 0 <= self.start <= self.end <= len(original) and (
            original[self.start : self.end] == self.quote
        )

length property

length: int

Character length of the grounded span.

verify

verify(original: str) -> bool

Whether original[start:end] still equals the stored quote.

Source code in src/fhirground/grounding.py
def verify(self, original: str) -> bool:
    """Whether ``original[start:end]`` still equals the stored quote."""
    return 0 <= self.start <= self.end <= len(original) and (
        original[self.start : self.end] == self.quote
    )

GroundingStrategy

Bases: StrEnum

How an evidence quote was located. Recorded on the evidence extension.

Source code in src/fhirground/grounding.py
class GroundingStrategy(StrEnum):
    """How an evidence quote was located. Recorded on the evidence extension."""

    EXACT = "exact"
    NORMALIZED = "normalized"
    FUZZY = "fuzzy"

ground_mention

ground_mention(
    evidence: str,
    chunks: list[Chunk],
    original: str,
    *,
    preferred_chunk_id: str | None = None,
    fuzzy_threshold: float = DEFAULT_FUZZY_THRESHOLD,
) -> Grounding | None

Locate evidence across chunks, preferring the chunk it came from.

The preferred chunk is tried first because overlap means the same sentence may appear in two chunks, and the offsets should attribute to the chunk the model actually saw. Other chunks are then tried so that a quote spanning a boundary still grounds.

Returns:

Type Description
Grounding | None

The best :class:Grounding found, or None.

Source code in src/fhirground/grounding.py
def ground_mention(
    evidence: str,
    chunks: list[Chunk],
    original: str,
    *,
    preferred_chunk_id: str | None = None,
    fuzzy_threshold: float = DEFAULT_FUZZY_THRESHOLD,
) -> Grounding | None:
    """Locate evidence across chunks, preferring the chunk it came from.

    The preferred chunk is tried first because overlap means the same sentence
    may appear in two chunks, and the offsets should attribute to the chunk the
    model actually saw. Other chunks are then tried so that a quote spanning a
    boundary still grounds.

    Returns:
        The best :class:`Grounding` found, or None.
    """
    ordered = list(chunks)
    if preferred_chunk_id is not None:
        ordered.sort(key=lambda c: c.chunk_id != preferred_chunk_id)

    best: Grounding | None = None
    for chunk in ordered:
        found = ground_in_chunk(evidence, chunk, original, fuzzy_threshold=fuzzy_threshold)
        if found is None:
            continue
        if found.strategy is GroundingStrategy.EXACT:
            return found
        if best is None or found.score > best.score:
            best = found
    return best

ground_in_chunk

ground_in_chunk(
    evidence: str,
    chunk: Chunk,
    original: str,
    *,
    fuzzy_threshold: float = DEFAULT_FUZZY_THRESHOLD,
) -> Grounding | None

Locate evidence inside one chunk, returning original-text offsets.

Parameters:

Name Type Description Default
evidence str

The model's quote.

required
chunk Chunk

The chunk the mention was extracted from.

required
original str

The full original note text, used to store the real quote.

required
fuzzy_threshold float

Minimum partial_ratio for a fuzzy hit.

DEFAULT_FUZZY_THRESHOLD

Returns:

Name Type Description
A Grounding | None

class:Grounding, or None if the quote could not be located.

Source code in src/fhirground/grounding.py
def ground_in_chunk(
    evidence: str,
    chunk: Chunk,
    original: str,
    *,
    fuzzy_threshold: float = DEFAULT_FUZZY_THRESHOLD,
) -> Grounding | None:
    """Locate ``evidence`` inside one chunk, returning original-text offsets.

    Args:
        evidence: The model's quote.
        chunk: The chunk the mention was extracted from.
        original: The full original note text, used to store the real quote.
        fuzzy_threshold: Minimum ``partial_ratio`` for a fuzzy hit.

    Returns:
        A :class:`Grounding`, or None if the quote could not be located.
    """
    if not evidence or not evidence.strip():
        return None

    hay = chunk.text

    hit = _find_exact(hay, evidence)
    if hit is not None:
        local, more = hit
        start = chunk.to_original(local)
        end = start + len(evidence)
        return Grounding(
            start=start,
            end=end,
            quote=original[start:end],
            strategy=GroundingStrategy.EXACT,
            score=1.0,
            ambiguous=more,
            chunk_id=chunk.chunk_id,
        )

    norm_hit = _find_normalized(hay, evidence)
    if norm_hit is not None:
        local_start, local_end, more = norm_hit
        start, end = chunk.to_original(local_start), chunk.to_original(local_end)
        return Grounding(
            start=start,
            end=end,
            quote=original[start:end],
            strategy=GroundingStrategy.NORMALIZED,
            score=0.9,
            ambiguous=more,
            chunk_id=chunk.chunk_id,
        )

    fuzzy_hit = _find_fuzzy(hay, evidence, fuzzy_threshold)
    if fuzzy_hit is not None:
        local_start, local_end, ratio = fuzzy_hit
        start, end = chunk.to_original(local_start), chunk.to_original(local_end)
        return Grounding(
            start=start,
            end=end,
            quote=original[start:end],
            strategy=GroundingStrategy.FUZZY,
            score=round((ratio / 100.0) * 0.8, 4),
            ambiguous=False,
            chunk_id=chunk.chunk_id,
        )

    return None

normalize

normalize(text: str) -> str

Collapse whitespace and fold case, for normalized matching.

Source code in src/fhirground/grounding.py
def normalize(text: str) -> str:
    """Collapse whitespace and fold case, for normalized matching."""
    return _WS.sub(" ", text).strip().lower()

The assertion policy

fhirground.assertion

Assertion policy: which mentions become resources, and in what state.

This is SPEC §4.4 as executable code. It is the module that keeps "denies chest pain" from becoming a Condition and "mother has hypertension" from becoming the patient's diagnosis -- the failure mode that makes naive note-to-FHIR pipelines dangerous rather than merely inaccurate.

The policy is deliberately a lookup, not a heuristic. Every row of the §4.4 table is a test case, and a mention whose combination is not in the table is dropped with reason unsupported rather than guessed at.

EmissionDecision dataclass

What to do with one mention.

Attributes:

Name Type Description
emit bool

Whether a resource should be produced.

reason DropReason | None

Why not, when emit is False.

verification_status VerificationStatus | None

For Conditions.

request_status RequestStatus | None

For MedicationRequests.

use_clinical_status_hint bool

Whether the mapper may set clinicalStatus from the model's hint. False means omit the field rather than default it to active.

note str

Short human-readable explanation, carried into the debug trace.

Source code in src/fhirground/assertion.py
@dataclass(frozen=True, slots=True)
class EmissionDecision:
    """What to do with one mention.

    Attributes:
        emit: Whether a resource should be produced.
        reason: Why not, when ``emit`` is False.
        verification_status: For Conditions.
        request_status: For MedicationRequests.
        use_clinical_status_hint: Whether the mapper may set
            ``clinicalStatus`` from the model's hint. False means omit the
            field rather than default it to ``active``.
        note: Short human-readable explanation, carried into the debug trace.
    """

    emit: bool
    reason: DropReason | None = None
    verification_status: VerificationStatus | None = None
    request_status: RequestStatus | None = None
    use_clinical_status_hint: bool = False
    note: str = ""

DropReason

Bases: StrEnum

Why a mention did not become a resource.

Counted and reported per note. A pipeline that drops most of what it finds is not working, so these counts are part of the run summary rather than buried in a debug file.

Source code in src/fhirground/assertion.py
class DropReason(StrEnum):
    """Why a mention did not become a resource.

    Counted and reported per note. A pipeline that drops most of what it finds
    is not working, so these counts are part of the run summary rather than
    buried in a debug file.
    """

    UNGROUNDED = "ungrounded"
    NEGATED = "negated"
    FAMILY = "family"
    HYPOTHETICAL = "hypothetical"
    MED_MENTION_ONLY = "med_mention_only"
    VALIDATION_FAILED = "validation_failed"
    BELOW_THRESHOLD = "below_threshold"
    UNSUPPORTED = "unsupported"
    NON_PATIENT_SECTION = "non_patient_section"

VerificationStatus

Bases: StrEnum

FHIR Condition.verificationStatus values used by v1.

Source code in src/fhirground/assertion.py
class VerificationStatus(StrEnum):
    """FHIR ``Condition.verificationStatus`` values used by v1."""

    CONFIRMED = "confirmed"
    PROVISIONAL = "provisional"
    REFUTED = "refuted"

RequestStatus

Bases: StrEnum

FHIR MedicationRequest.status values used by v1.

Source code in src/fhirground/assertion.py
class RequestStatus(StrEnum):
    """FHIR ``MedicationRequest.status`` values used by v1."""

    ACTIVE = "active"
    STOPPED = "stopped"

decide

decide(
    mention: Mention,
    *,
    emit_refuted: bool = False,
    section: str | None = None,
    respect_non_patient_sections: bool = True,
) -> EmissionDecision

Apply the §4.4 policy to one mention.

Parameters:

Name Type Description Default
mention Mention

The grounded mention.

required
emit_refuted bool

When true, a negated condition is emitted with verificationStatus=refuted instead of being dropped. Off by default: most consumers want asserted findings, and a refuted Condition in a Bundle is easy to misread as a positive one.

False
section str | None

Name of the note section the mention came from.

None
respect_non_patient_sections bool

When true, a mention from a family-history section is dropped as family even if the model labelled it present. The section is better evidence than the sentence, because "hypertension" under Family History carries no negation cue for a model to notice.

True

Returns:

Name Type Description
An EmissionDecision

class:EmissionDecision.

Source code in src/fhirground/assertion.py
def decide(
    mention: Mention,
    *,
    emit_refuted: bool = False,
    section: str | None = None,
    respect_non_patient_sections: bool = True,
) -> EmissionDecision:
    """Apply the §4.4 policy to one mention.

    Args:
        mention: The grounded mention.
        emit_refuted: When true, a negated condition is emitted with
            ``verificationStatus=refuted`` instead of being dropped. Off by
            default: most consumers want asserted findings, and a refuted
            Condition in a Bundle is easy to misread as a positive one.
        section: Name of the note section the mention came from.
        respect_non_patient_sections: When true, a mention from a
            family-history section is dropped as family even if the model
            labelled it ``present``. The section is better evidence than the
            sentence, because "hypertension" under *Family History* carries no
            negation cue for a model to notice.

    Returns:
        An :class:`EmissionDecision`.
    """
    from fhirground.preprocess.sections import is_non_patient_section

    if respect_non_patient_sections and is_non_patient_section(section):
        return EmissionDecision(
            emit=False,
            reason=DropReason.FAMILY,
            note=f"mention appeared under the {section!r} section",
        )

    # Assertions that are dropped regardless of mention type.
    if mention.assertion is Assertion.FAMILY:
        return EmissionDecision(
            emit=False,
            reason=DropReason.FAMILY,
            note="family history; FamilyMemberHistory is out of scope in v1",
        )
    if mention.assertion is Assertion.HYPOTHETICAL:
        return EmissionDecision(
            emit=False,
            reason=DropReason.HYPOTHETICAL,
            note="hypothetical or conditional mention",
        )

    if mention.mention_type is MentionType.CONDITION:
        return _decide_condition(mention, emit_refuted=emit_refuted)
    if mention.mention_type is MentionType.MEDICATION:
        return _decide_medication(mention)
    if mention.mention_type is MentionType.OBSERVATION:
        return _decide_observation(mention)

    return EmissionDecision(  # pragma: no cover - MentionType is exhaustive
        emit=False, reason=DropReason.UNSUPPORTED, note="unknown mention type"
    )

Normalization

fhirground.normalize.units

Common clinical units mapped to UCUM.

A bundled table of roughly sixty units, which covers what appears in vitals and routine labs. It is not a UCUM implementation: no parsing of arbitrary expressions, no arithmetic on dimensions.

The rule that matters: a unit fhirground does not recognize is kept as valueQuantity.unit text only, with no system and no code. Emitting http://unitsofmeasure.org beside a guessed code would be a hallucinated code wearing a standards URL, which is precisely what this project exists to avoid. A project validation rule enforces it.

UnitResolution dataclass

The outcome of looking up a unit string.

Attributes:

Name Type Description
text str

The unit as written, preserved for valueQuantity.unit.

code str | None

UCUM code, or None when unrecognized.

system str | None

:data:UCUM_SYSTEM when a code was found, else None.

Source code in src/fhirground/normalize/units.py
@dataclass(frozen=True, slots=True)
class UnitResolution:
    """The outcome of looking up a unit string.

    Attributes:
        text: The unit as written, preserved for ``valueQuantity.unit``.
        code: UCUM code, or None when unrecognized.
        system: :data:`UCUM_SYSTEM` when a code was found, else None.
    """

    text: str
    code: str | None = None
    system: str | None = None

    @property
    def is_ucum(self) -> bool:
        """Whether a UCUM code was found."""
        return self.code is not None

is_ucum property

is_ucum: bool

Whether a UCUM code was found.

resolve_unit

resolve_unit(raw: str | None) -> UnitResolution | None

Look up a unit string in the bundled table.

Returns:

Name Type Description
A UnitResolution | None

class:UnitResolution. When the unit is not in the table, code

UnitResolution | None

and system are None and only the original text is carried -- never

UnitResolution | None

a guessed code. Returns None for an absent or blank input.

Source code in src/fhirground/normalize/units.py
def resolve_unit(raw: str | None) -> UnitResolution | None:
    """Look up a unit string in the bundled table.

    Returns:
        A :class:`UnitResolution`. When the unit is not in the table, ``code``
        and ``system`` are None and only the original text is carried -- never
        a guessed code. Returns None for an absent or blank input.
    """
    if raw is None:
        return None
    text = raw.strip()
    if not text:
        return None

    key = normalize_unit_key(text)
    code = UCUM_TABLE.get(key)
    if code is None:
        # A trailing period or plural "s" is common in free text.
        for variant in (key.rstrip("."), key.rstrip("s"), key.rstrip(".s")):
            if variant and variant in UCUM_TABLE:
                code = UCUM_TABLE[variant]
                break

    if code is None:
        return UnitResolution(text=text)
    return UnitResolution(text=text, code=code, system=UCUM_SYSTEM)

is_known_ucum_code

is_known_ucum_code(code: str | None) -> bool

Whether code is one this table can produce.

Used by the project validation rule that forbids the UCUM system appearing beside a code fhirground did not resolve itself.

Source code in src/fhirground/normalize/units.py
def is_known_ucum_code(code: str | None) -> bool:
    """Whether ``code`` is one this table can produce.

    Used by the project validation rule that forbids the UCUM system appearing
    beside a code fhirground did not resolve itself.
    """
    return code is not None and code in set(UCUM_TABLE.values())

known_unit_count

known_unit_count() -> int

Number of distinct UCUM codes in the bundled table.

Source code in src/fhirground/normalize/units.py
def known_unit_count() -> int:
    """Number of distinct UCUM codes in the bundled table."""
    return len(set(UCUM_TABLE.values()))

fhirground.normalize.values

Parsing numeric values, comparators, and simple ranges.

The cases that actually appear in notes: 9.2, <0.01, >= 140, 120/80, 5-10. Anything more exotic is left as text rather than guessed at, because a wrong number in a FHIR Observation is worse than a string.

Ranges are a deliberate compromise, specified in SPEC §3.8: the low bound becomes the value and a note records the original range. A FHIR valueQuantity holds one number, and silently discarding the upper bound without saying so would be the kind of quiet lossiness this project is meant to avoid.

ParsedValue dataclass

A parsed observation or dose value.

Attributes:

Name Type Description
number float | None

The numeric value, or None when the text did not parse.

comparator ValueComparator | None

A FHIR Quantity.comparator, when one was written.

text str

The original text, always preserved.

is_range bool

True when the input was a range and number is its low bound.

range_high float | None

The upper bound of a range, kept for the note.

note str

Human-readable caveat, carried into Observation.note and the debug trace. Non-empty exactly when information was dropped.

kind str

number, comparator, range, pair, or text.

Source code in src/fhirground/normalize/values.py
@dataclass(frozen=True, slots=True)
class ParsedValue:
    """A parsed observation or dose value.

    Attributes:
        number: The numeric value, or None when the text did not parse.
        comparator: A FHIR ``Quantity.comparator``, when one was written.
        text: The original text, always preserved.
        is_range: True when the input was a range and ``number`` is its low
            bound.
        range_high: The upper bound of a range, kept for the note.
        note: Human-readable caveat, carried into ``Observation.note`` and the
            debug trace. Non-empty exactly when information was dropped.
        kind: ``number``, ``comparator``, ``range``, ``pair``, or ``text``.
    """

    number: float | None = None
    comparator: ValueComparator | None = None
    text: str = ""
    is_range: bool = False
    range_high: float | None = None
    note: str = ""
    kind: str = "text"

    @property
    def is_numeric(self) -> bool:
        """Whether a number was recovered."""
        return self.number is not None

is_numeric property

is_numeric: bool

Whether a number was recovered.

parse_value

parse_value(
    raw: str | float | int | None,
) -> ParsedValue | None

Parse a value expression from a mention.

Parameters:

Name Type Description Default
raw str | float | int | None

The value as written, or an already-numeric value.

required

Returns:

Name Type Description
A ParsedValue | None

class:ParsedValue, or None for an absent or blank input.

Source code in src/fhirground/normalize/values.py
def parse_value(raw: str | float | int | None) -> ParsedValue | None:
    """Parse a value expression from a mention.

    Args:
        raw: The value as written, or an already-numeric value.

    Returns:
        A :class:`ParsedValue`, or None for an absent or blank input.
    """
    if raw is None:
        return None
    if isinstance(raw, (int, float)) and not isinstance(raw, bool):
        return ParsedValue(number=float(raw), text=str(raw), kind="number")

    text = str(raw).strip()
    if not text:
        return None

    plain = _PLAIN_RE.match(text)
    if plain:
        value = _to_float(plain.group("num"))
        if value is not None:
            return ParsedValue(number=value, text=text, kind="number")

    comparator = _COMPARATOR_RE.match(text)
    if comparator:
        value = _to_float(comparator.group("num"))
        if value is not None:
            return ParsedValue(
                number=value,
                comparator=_COMPARATORS[comparator.group("cmp")],
                text=text,
                kind="comparator",
            )

    ranged = _RANGE_RE.match(text)
    if ranged:
        low, high = _to_float(ranged.group("low")), _to_float(ranged.group("high"))
        if low is not None and high is not None and low <= high:
            return ParsedValue(
                number=low,
                text=text,
                is_range=True,
                range_high=high,
                note=(
                    f"Reported as a range {text!r}; the low bound is recorded as the "
                    "value and the upper bound is not represented in valueQuantity."
                ),
                kind="range",
            )

    pair = _BP_RE.match(text)
    if pair:
        return ParsedValue(
            text=text,
            note=(
                f"Reported as a pair {text!r}, which is two measurements. v1 keeps it "
                "as valueString rather than splitting it into components."
            ),
            kind="pair",
        )

    return ParsedValue(text=text, kind="text")

parse_dose

parse_dose(
    dose_value: float | None, dose_unit: str | None
) -> tuple[float, str] | None

Validate a dose pair for doseAndRate[0].doseQuantity.

Returns:

Type Description
tuple[float, str] | None

(value, unit_text) only when both are present and the value is a

tuple[float, str] | None

finite, non-negative number. A dose without a unit is meaningless and a

tuple[float, str] | None

unit without a value is not a dose, so either alone yields None and the

tuple[float, str] | None

information survives in dosageInstruction.text.

Source code in src/fhirground/normalize/values.py
def parse_dose(dose_value: float | None, dose_unit: str | None) -> tuple[float, str] | None:
    """Validate a dose pair for ``doseAndRate[0].doseQuantity``.

    Returns:
        ``(value, unit_text)`` only when both are present and the value is a
        finite, non-negative number. A dose without a unit is meaningless and a
        unit without a value is not a dose, so either alone yields None and the
        information survives in ``dosageInstruction.text``.
    """
    if dose_value is None or dose_unit is None:
        return None
    unit = dose_unit.strip()
    if not unit:
        return None
    try:
        value = float(dose_value)
    except (TypeError, ValueError):
        return None
    if value < 0 or value != value or value in (float("inf"), float("-inf")):
        return None
    return value, unit

fhirground.normalize.dates

Resolving dates and relative phrases against the note's timestamp.

Explicit dates (ISO, MM/DD/YYYY, Month D, YYYY) and a small set of relative phrases (today, yesterday, N days/weeks/months ago). Everything else resolves to None, and None is honest: a wrong effectiveDateTime silently misdates a clinical finding, and "last winter" has no defensible answer.

MM/DD/YYYY is read US-style, which is the convention in US clinical notes and in the Synthea fixtures. The ambiguity with DD/MM is real, so :func:resolve_date reports which interpretation it used and refuses the genuinely ambiguous slash dates when day_first is left unset and both readings are valid.

ResolvedDate dataclass

A date recovered from text.

Attributes:

Name Type Description
value date

The resolved date.

precision str

day, month, or year -- what the text supported.

strategy str

How it was resolved, for the debug trace.

text str

The original phrase.

inferred bool

True when the date came from the note timestamp rather than from the text. Drives the effective-inferred extension.

Source code in src/fhirground/normalize/dates.py
@dataclass(frozen=True, slots=True)
class ResolvedDate:
    """A date recovered from text.

    Attributes:
        value: The resolved date.
        precision: ``day``, ``month``, or ``year`` -- what the text supported.
        strategy: How it was resolved, for the debug trace.
        text: The original phrase.
        inferred: True when the date came from the note timestamp rather than
            from the text. Drives the ``effective-inferred`` extension.
    """

    value: date
    precision: str
    strategy: str
    text: str
    inferred: bool = False

    def to_fhir(self) -> str:
        """FHIR ``date``/``dateTime`` string at the stated precision.

        A month-precision onset becomes ``2019-03``, not ``2019-03-01``.
        Padding to a day fabricates precision the note never had.
        """
        if self.precision == DatePrecision.YEAR:
            return f"{self.value.year:04d}"
        if self.precision == DatePrecision.MONTH:
            return f"{self.value.year:04d}-{self.value.month:02d}"
        return self.value.isoformat()

to_fhir

to_fhir() -> str

FHIR date/dateTime string at the stated precision.

A month-precision onset becomes 2019-03, not 2019-03-01. Padding to a day fabricates precision the note never had.

Source code in src/fhirground/normalize/dates.py
def to_fhir(self) -> str:
    """FHIR ``date``/``dateTime`` string at the stated precision.

    A month-precision onset becomes ``2019-03``, not ``2019-03-01``.
    Padding to a day fabricates precision the note never had.
    """
    if self.precision == DatePrecision.YEAR:
        return f"{self.value.year:04d}"
    if self.precision == DatePrecision.MONTH:
        return f"{self.value.year:04d}-{self.value.month:02d}"
    return self.value.isoformat()

DatePrecision

How much of the date was actually stated.

Source code in src/fhirground/normalize/dates.py
class DatePrecision:
    """How much of the date was actually stated."""

    DAY = "day"
    MONTH = "month"
    YEAR = "year"

resolve_date

resolve_date(
    text: str | None,
    note_datetime: datetime,
    *,
    day_first: bool | None = None,
) -> ResolvedDate | None

Resolve a date phrase against the note's timestamp.

Parameters:

Name Type Description Default
text str | None

The phrase as written, e.g. "3 days ago" or "03/14/2026".

required
note_datetime datetime

Anchor for relative phrases.

required
day_first bool | None

Interpretation for A/B/YYYY. False forces US month-first, True forces day-first, and None (the default) uses month-first but refuses dates where both readings are valid and different -- better no date than a date six months off.

None

Returns:

Name Type Description
A ResolvedDate | None

class:ResolvedDate, or None when nothing could be resolved.

Source code in src/fhirground/normalize/dates.py
def resolve_date(
    text: str | None,
    note_datetime: datetime,
    *,
    day_first: bool | None = None,
) -> ResolvedDate | None:
    """Resolve a date phrase against the note's timestamp.

    Args:
        text: The phrase as written, e.g. ``"3 days ago"`` or ``"03/14/2026"``.
        note_datetime: Anchor for relative phrases.
        day_first: Interpretation for ``A/B/YYYY``. ``False`` forces US
            month-first, ``True`` forces day-first, and ``None`` (the default)
            uses month-first but **refuses** dates where both readings are
            valid and different -- better no date than a date six months off.

    Returns:
        A :class:`ResolvedDate`, or None when nothing could be resolved.
    """
    if not text:
        return None
    phrase = text.strip()
    if not phrase:
        return None

    anchor = note_datetime.date()

    iso = _ISO_RE.search(phrase)
    if iso:
        value = _safe_date(int(iso["y"]), int(iso["m"]), int(iso["d"]))
        if value:
            return _mk(value, DatePrecision.DAY, "iso", phrase)

    slash = _SLASH_RE.search(phrase)
    if slash:
        a, b = int(slash["a"]), int(slash["b"])
        year = int(slash["y"])
        if year < 100:
            year += 2000 if year <= (anchor.year % 100) else 1900
        month_first = _safe_date(year, a, b)
        day_first_value = _safe_date(year, b, a)
        if day_first is True and day_first_value:
            return _mk(day_first_value, DatePrecision.DAY, "slash_day_first", phrase)
        if day_first is False and month_first:
            return _mk(month_first, DatePrecision.DAY, "slash_month_first", phrase)
        if day_first is None:
            if month_first and day_first_value and month_first != day_first_value:
                # Genuinely ambiguous: 03/04/2026 could be either.
                return None
            if month_first:
                return _mk(month_first, DatePrecision.DAY, "slash_month_first", phrase)
            if day_first_value:
                return _mk(day_first_value, DatePrecision.DAY, "slash_day_first", phrase)

    named = _MONTH_NAME_RE.search(phrase)
    if named:
        month = _MONTHS.get(named["mon"].lower())
        if month:
            value = _safe_date(int(named["y"]), month, int(named["d"]))
            if value:
                return _mk(value, DatePrecision.DAY, "month_name", phrase)

    day_month = _DAY_MONTH_RE.search(phrase)
    if day_month:
        month = _MONTHS.get(day_month["mon"].lower())
        if month:
            value = _safe_date(int(day_month["y"]), month, int(day_month["d"]))
            if value:
                return _mk(value, DatePrecision.DAY, "day_month_name", phrase)

    relative = _RELATIVE_RE.search(phrase)
    if relative:
        token = relative["n"].lower()
        count = _WORD_NUMBERS.get(token) if not token.isdigit() else int(token)
        if count is not None:
            unit = relative["unit"].lower().rstrip("s")
            if unit == "day":
                return _mk(anchor - timedelta(days=count), DatePrecision.DAY, "relative", phrase)
            if unit == "week":
                return _mk(anchor - timedelta(weeks=count), DatePrecision.DAY, "relative", phrase)
            if unit == "month":
                return _mk(_shift_months(anchor, -count), DatePrecision.MONTH, "relative", phrase)
            if unit in ("year", "yr"):
                return _mk(
                    _shift_months(anchor, -12 * count), DatePrecision.YEAR, "relative", phrase
                )

    if _TODAY_RE.search(phrase):
        return _mk(anchor, DatePrecision.DAY, "today", phrase)
    if _YESTERDAY_RE.search(phrase):
        return _mk(anchor - timedelta(days=1), DatePrecision.DAY, "yesterday", phrase)

    month_year = _MONTH_YEAR_RE.search(phrase)
    if month_year:
        month = _MONTHS.get(month_year["mon"].lower())
        if month:
            value = _safe_date(int(month_year["y"]), month, 1)
            if value:
                return _mk(value, DatePrecision.MONTH, "month_year", phrase)

    year_only = _YEAR_ONLY_RE.search(phrase)
    if year_only:
        value = _safe_date(int(year_only["y"]), 1, 1)
        if value:
            return _mk(value, DatePrecision.YEAR, "year_only", phrase)

    return None

inferred_from_note

inferred_from_note(note_datetime: datetime) -> ResolvedDate

The note timestamp, marked as inferred.

Used for an Observation with no resolvable date, so the resource carries a usable effectiveDateTime while the effective-inferred extension records that fhirground supplied it rather than the note.

Source code in src/fhirground/normalize/dates.py
def inferred_from_note(note_datetime: datetime) -> ResolvedDate:
    """The note timestamp, marked as inferred.

    Used for an Observation with no resolvable date, so the resource carries a
    usable ``effectiveDateTime`` while the ``effective-inferred`` extension
    records that fhirground supplied it rather than the note.
    """
    return ResolvedDate(
        value=note_datetime.date(),
        precision=DatePrecision.DAY,
        strategy="note_datetime",
        text="",
        inferred=True,
    )

Terminology

fhirground.terminology.base

The terminology interface: the only door a code may come through.

SPEC §0 states the hard rule -- the LLM never emits medical codes -- and this module is how that rule is made structural rather than aspirational.

Two mechanisms, together:

  1. The mention schema has no code fields, so a model has nowhere to put one.
  2. Every mapping function accepts a :class:Resolution and never a raw string. A code therefore cannot reach a FHIR resource without having been constructed by a resolver, and a resolver only returns codes that came from its own value sets.

A property test drives adversarial mentions (text containing "SNOMED 44054006") through the pipeline and asserts that every coding.code in the output exists in the active resolvers' value sets.

TerminologyResolver

Bases: Protocol

Anything that can turn mention text into a code.

Implementations must return a :class:Resolution or None, and must never fabricate a code that is not in their own source data.

Source code in src/fhirground/terminology/base.py
@runtime_checkable
class TerminologyResolver(Protocol):
    """Anything that can turn mention text into a code.

    Implementations must return a :class:`Resolution` or None, and must never
    fabricate a code that is not in their own source data.
    """

    name: str

    def resolve(
        self, text: str, mention_type: MentionType, context: dict[str, Any] | None = None
    ) -> Resolution | None:
        """Resolve ``text`` to a code, or return None to pass to the next resolver."""
        ...

    def known_codes(self) -> set[tuple[str, str]]:
        """Every ``(system, code)`` this resolver could possibly emit.

        Used by the no-invented-codes property test: the union over active
        resolvers is the allowed set, and any code outside it is a bug. A
        network resolver returns what it has cached, and the test marks
        remote-resolved codes separately.
        """
        ...

resolve

resolve(
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None

Resolve text to a code, or return None to pass to the next resolver.

Source code in src/fhirground/terminology/base.py
def resolve(
    self, text: str, mention_type: MentionType, context: dict[str, Any] | None = None
) -> Resolution | None:
    """Resolve ``text`` to a code, or return None to pass to the next resolver."""
    ...

known_codes

known_codes() -> set[tuple[str, str]]

Every (system, code) this resolver could possibly emit.

Used by the no-invented-codes property test: the union over active resolvers is the allowed set, and any code outside it is a bug. A network resolver returns what it has cached, and the test marks remote-resolved codes separately.

Source code in src/fhirground/terminology/base.py
def known_codes(self) -> set[tuple[str, str]]:
    """Every ``(system, code)`` this resolver could possibly emit.

    Used by the no-invented-codes property test: the union over active
    resolvers is the allowed set, and any code outside it is a bug. A
    network resolver returns what it has cached, and the test marks
    remote-resolved codes separately.
    """
    ...

Resolution dataclass

The outcome of resolving one mention's text to a code.

A resolution with coding=None is a legitimate, expected result: SPEC design principle 3 says an unresolved mention becomes a text-only CodeableConcept and the confidence reflects it. Returning None-with-text rather than refusing to emit is what keeps recall usable without inventing codes.

Attributes:

Name Type Description
text str

The text that was resolved, preserved for code.text.

coding Coding | None

The code, or None for a text-only concept.

score float

Match confidence in [0, 1]; the terminology component of the resource's confidence.

resolver str

Name of the resolver that produced this, for the debug trace.

method str

exact, synonym, fuzzy, remote, or none.

candidates tuple[tuple[str, float], ...]

Runner-up matches, recorded for review when a fuzzy match was close.

Source code in src/fhirground/terminology/base.py
@dataclass(frozen=True, slots=True)
class Resolution:
    """The outcome of resolving one mention's text to a code.

    A resolution with ``coding=None`` is a legitimate, expected result: SPEC
    design principle 3 says an unresolved mention becomes a text-only
    ``CodeableConcept`` and the confidence reflects it. Returning None-with-text
    rather than refusing to emit is what keeps recall usable without inventing
    codes.

    Attributes:
        text: The text that was resolved, preserved for ``code.text``.
        coding: The code, or None for a text-only concept.
        score: Match confidence in [0, 1]; the terminology component of the
            resource's confidence.
        resolver: Name of the resolver that produced this, for the debug trace.
        method: ``exact``, ``synonym``, ``fuzzy``, ``remote``, or ``none``.
        candidates: Runner-up matches, recorded for review when a fuzzy match
            was close.
    """

    text: str
    coding: Coding | None = None
    score: float = 0.0
    resolver: str = ""
    method: str = "none"
    candidates: tuple[tuple[str, float], ...] = field(default_factory=tuple)

    @property
    def is_coded(self) -> bool:
        """Whether a code was found."""
        return self.coding is not None

    def as_codeable_concept(self) -> dict[str, Any]:
        """FHIR ``CodeableConcept``, coded or text-only.

        ``text`` is always present. A consumer that cannot use the code can
        still read what the note said, and a text-only concept is visibly
        text-only rather than silently empty.
        """
        out: dict[str, Any] = {"text": self.text}
        if self.coding is not None:
            out["coding"] = [self.coding.as_fhir()]
        return out

is_coded property

is_coded: bool

Whether a code was found.

as_codeable_concept

as_codeable_concept() -> dict[str, Any]

FHIR CodeableConcept, coded or text-only.

text is always present. A consumer that cannot use the code can still read what the note said, and a text-only concept is visibly text-only rather than silently empty.

Source code in src/fhirground/terminology/base.py
def as_codeable_concept(self) -> dict[str, Any]:
    """FHIR ``CodeableConcept``, coded or text-only.

    ``text`` is always present. A consumer that cannot use the code can
    still read what the note said, and a text-only concept is visibly
    text-only rather than silently empty.
    """
    out: dict[str, Any] = {"text": self.text}
    if self.coding is not None:
        out["coding"] = [self.coding.as_fhir()]
    return out

Coding dataclass

A terminology code, with the system it belongs to.

Frozen and constructed only by resolvers. display is the value set's own display string, never the model's wording -- otherwise a resource could carry a code from the terminology beside a label the model invented.

Source code in src/fhirground/terminology/base.py
@dataclass(frozen=True, slots=True)
class Coding:
    """A terminology code, with the system it belongs to.

    Frozen and constructed only by resolvers. ``display`` is the value set's
    own display string, never the model's wording -- otherwise a resource
    could carry a code from the terminology beside a label the model invented.
    """

    system: str
    code: str
    display: str | None = None

    def as_fhir(self) -> dict[str, Any]:
        """FHIR ``Coding`` element."""
        out: dict[str, Any] = {"system": self.system, "code": self.code}
        if self.display:
            out["display"] = self.display
        return out

as_fhir

as_fhir() -> dict[str, Any]

FHIR Coding element.

Source code in src/fhirground/terminology/base.py
def as_fhir(self) -> dict[str, Any]:
    """FHIR ``Coding`` element."""
    out: dict[str, Any] = {"system": self.system, "code": self.code}
    if self.display:
        out["display"] = self.display
    return out

ResolverConfig dataclass

Which resolver handles which mention type.

Per-type rather than global because the terminologies differ: conditions go to SNOMED CT or ICD-10, medications to RxNorm, observations to LOINC. One resolver over all three would have to search every value set for every mention, which is both slower and more likely to cross-match.

Source code in src/fhirground/terminology/base.py
@dataclass
class ResolverConfig:
    """Which resolver handles which mention type.

    Per-type rather than global because the terminologies differ: conditions go
    to SNOMED CT or ICD-10, medications to RxNorm, observations to LOINC. One
    resolver over all three would have to search every value set for every
    mention, which is both slower and more likely to cross-match.
    """

    condition: TerminologyResolver | None = None
    medication: TerminologyResolver | None = None
    observation: TerminologyResolver | None = None

    def for_type(self, mention_type: MentionType) -> TerminologyResolver | None:
        """The resolver for a mention type, or None."""
        return {
            MentionType.CONDITION: self.condition,
            MentionType.MEDICATION: self.medication,
            MentionType.OBSERVATION: self.observation,
        }[mention_type]

    def resolve(
        self,
        text: str,
        mention_type: MentionType,
        context: dict[str, Any] | None = None,
    ) -> Resolution:
        """Resolve through the configured resolver, falling back to text-only.

        Always returns a :class:`Resolution`, never None, so callers do not
        have to decide what an absent resolver means. With no resolver
        configured the result is text-only with score 0.0, which is the honest
        representation of "nobody looked".
        """
        resolver = self.for_type(mention_type)
        if resolver is None:
            return Resolution(text=text, resolver="none", method="none", score=0.0)
        found = resolver.resolve(text, mention_type, context)
        if found is None:
            return Resolution(text=text, resolver=resolver.name, method="none", score=0.0)
        return found

    def all_known_codes(self) -> set[tuple[str, str]]:
        """Union of every code the configured resolvers could emit."""
        out: set[tuple[str, str]] = set()
        for resolver in (self.condition, self.medication, self.observation):
            if resolver is not None:
                out |= resolver.known_codes()
        return out

    def describe(self) -> dict[str, str]:
        """Resolver name per mention type, for the run summary."""
        return {
            "condition": self.condition.name if self.condition else "none",
            "medication": self.medication.name if self.medication else "none",
            "observation": self.observation.name if self.observation else "none",
        }

for_type

for_type(
    mention_type: MentionType,
) -> TerminologyResolver | None

The resolver for a mention type, or None.

Source code in src/fhirground/terminology/base.py
def for_type(self, mention_type: MentionType) -> TerminologyResolver | None:
    """The resolver for a mention type, or None."""
    return {
        MentionType.CONDITION: self.condition,
        MentionType.MEDICATION: self.medication,
        MentionType.OBSERVATION: self.observation,
    }[mention_type]

resolve

resolve(
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution

Resolve through the configured resolver, falling back to text-only.

Always returns a :class:Resolution, never None, so callers do not have to decide what an absent resolver means. With no resolver configured the result is text-only with score 0.0, which is the honest representation of "nobody looked".

Source code in src/fhirground/terminology/base.py
def resolve(
    self,
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution:
    """Resolve through the configured resolver, falling back to text-only.

    Always returns a :class:`Resolution`, never None, so callers do not
    have to decide what an absent resolver means. With no resolver
    configured the result is text-only with score 0.0, which is the honest
    representation of "nobody looked".
    """
    resolver = self.for_type(mention_type)
    if resolver is None:
        return Resolution(text=text, resolver="none", method="none", score=0.0)
    found = resolver.resolve(text, mention_type, context)
    if found is None:
        return Resolution(text=text, resolver=resolver.name, method="none", score=0.0)
    return found

all_known_codes

all_known_codes() -> set[tuple[str, str]]

Union of every code the configured resolvers could emit.

Source code in src/fhirground/terminology/base.py
def all_known_codes(self) -> set[tuple[str, str]]:
    """Union of every code the configured resolvers could emit."""
    out: set[tuple[str, str]] = set()
    for resolver in (self.condition, self.medication, self.observation):
        if resolver is not None:
            out |= resolver.known_codes()
    return out

describe

describe() -> dict[str, str]

Resolver name per mention type, for the run summary.

Source code in src/fhirground/terminology/base.py
def describe(self) -> dict[str, str]:
    """Resolver name per mention type, for the run summary."""
    return {
        "condition": self.condition.name if self.condition else "none",
        "medication": self.medication.name if self.medication else "none",
        "observation": self.observation.name if self.observation else "none",
    }

fhirground.terminology.local

Local value-set resolvers: user-supplied CSV or JSON.

This is the resolver most deployments will use, because the real terminologies cannot be bundled. SNOMED CT, LOINC, and RxNorm each carry licensing obligations, so fhirground ships only tiny synthetic value sets for its tests and documentation, and the docs say plainly that a real deployment supplies its own.

Matching is two-stage: normalized exact match on the display or any synonym, then rapidfuzz token_set_ratio above a threshold. Token-set is the right choice for clinical text because it ignores word order and duplication -- "diabetes mellitus type 2" and "type 2 diabetes mellitus" are the same concept and a plain ratio would score them poorly.

LocalValueSet

A resolver backed by an in-memory value set.

Example::

conditions = LocalValueSet.from_csv("valuesets/conditions.csv")
conditions.resolve("type 2 diabetes", MentionType.CONDITION)
Source code in src/fhirground/terminology/local.py
class LocalValueSet:
    """A resolver backed by an in-memory value set.

    Example::

        conditions = LocalValueSet.from_csv("valuesets/conditions.csv")
        conditions.resolve("type 2 diabetes", MentionType.CONDITION)
    """

    def __init__(
        self,
        entries: list[ValueSetEntry],
        *,
        name: str = "local",
        fuzzy_threshold: float = DEFAULT_FUZZY_THRESHOLD,
        fuzzy: bool = True,
    ) -> None:
        if not entries:
            raise TerminologyError(
                f"value set {name!r} is empty; a resolver with no concepts can only "
                "ever return text-only resolutions, so use NullResolver instead"
            )
        self.name = name
        self.entries = entries
        self.fuzzy_threshold = fuzzy_threshold
        self.fuzzy = fuzzy

        # Surface form -> entry. Built once; the first entry wins a collision so
        # value-set order is the tie-break and the result is deterministic.
        self._index: dict[str, ValueSetEntry] = {}
        for entry in entries:
            for form in entry.surface_forms:
                key = _normalize(form)
                if key and key not in self._index:
                    self._index[key] = entry
        self._keys = list(self._index)

    def __len__(self) -> int:
        return len(self.entries)

    # -- construction ---------------------------------------------------

    @classmethod
    def from_csv(cls, path: str | Path, *, name: str | None = None, **kwargs: Any) -> LocalValueSet:
        """Load from a CSV with ``system,code,display,synonyms``.

        ``synonyms`` is pipe-separated, as SPEC §6.3 specifies.
        """
        path = Path(path)
        if not path.exists():
            raise TerminologyError(f"value set file not found: {path}")

        entries: list[ValueSetEntry] = []
        with path.open(encoding="utf-8-sig", newline="") as fh:
            reader = csv.DictReader(fh)
            if reader.fieldnames is None:
                raise TerminologyError(f"value set {path} has no header row")
            missing = [c for c in REQUIRED_COLUMNS if c not in reader.fieldnames]
            if missing:
                raise TerminologyError(
                    f"value set {path} is missing column(s) {missing}; "
                    f"required: {list(REQUIRED_COLUMNS)}, found: {reader.fieldnames}"
                )
            for lineno, row in enumerate(reader, start=2):
                system = (row.get("system") or "").strip()
                code = (row.get("code") or "").strip()
                display = (row.get("display") or "").strip()
                if not (system and code and display):
                    raise TerminologyError(
                        f"{path}:{lineno}: system, code, and display are all required"
                    )
                raw_syn = (row.get("synonyms") or "").strip()
                synonyms = tuple(s.strip() for s in raw_syn.split("|") if s.strip())
                entries.append(
                    ValueSetEntry(system=system, code=code, display=display, synonyms=synonyms)
                )
        return cls(entries, name=name or f"local:{path.stem}", **kwargs)

    @classmethod
    def from_json(
        cls, path: str | Path, *, name: str | None = None, **kwargs: Any
    ) -> LocalValueSet:
        """Load from a JSON list of ``{system, code, display, synonyms}``."""
        path = Path(path)
        if not path.exists():
            raise TerminologyError(f"value set file not found: {path}")
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except json.JSONDecodeError as exc:
            raise TerminologyError(f"{path}: malformed JSON: {exc.msg}") from exc
        if not isinstance(data, list):
            raise TerminologyError(f"{path}: expected a JSON array of concepts")

        entries = []
        for i, row in enumerate(data):
            if not isinstance(row, dict):
                raise TerminologyError(f"{path}: entry {i} is not an object")
            missing = [c for c in REQUIRED_COLUMNS if not row.get(c)]
            if missing:
                raise TerminologyError(f"{path}: entry {i} is missing {missing}")
            synonyms = row.get("synonyms") or []
            if isinstance(synonyms, str):
                synonyms = [s.strip() for s in synonyms.split("|") if s.strip()]
            entries.append(
                ValueSetEntry(
                    system=str(row["system"]),
                    code=str(row["code"]),
                    display=str(row["display"]),
                    synonyms=tuple(str(s) for s in synonyms),
                )
            )
        return cls(entries, name=name or f"local:{path.stem}", **kwargs)

    @classmethod
    def from_entries(
        cls, rows: list[dict[str, Any]], *, name: str = "local", **kwargs: Any
    ) -> LocalValueSet:
        """Build from plain dicts, for tests and programmatic use."""
        entries = []
        for row in rows:
            synonyms = row.get("synonyms") or ()
            if isinstance(synonyms, str):
                synonyms = tuple(s.strip() for s in synonyms.split("|") if s.strip())
            entries.append(
                ValueSetEntry(
                    system=str(row["system"]),
                    code=str(row["code"]),
                    display=str(row["display"]),
                    synonyms=tuple(synonyms),
                )
            )
        return cls(entries, name=name, **kwargs)

    # -- resolution -----------------------------------------------------

    def resolve(
        self,
        text: str,
        mention_type: MentionType,
        context: dict[str, Any] | None = None,
    ) -> Resolution | None:
        """Resolve text against this value set.

        Returns:
            A coded :class:`Resolution` on a hit, or None so a chain can try
            the next resolver. Scores: 1.0 for an exact display match, 0.95 for
            an exact synonym match, and ``ratio/100`` for a fuzzy hit.
        """
        _ = mention_type, context
        key = _normalize(text or "")
        if not key:
            return None

        entry = self._index.get(key)
        if entry is not None:
            exact_display = _normalize(entry.display) == key
            return Resolution(
                text=text,
                coding=entry.to_coding(),
                score=1.0 if exact_display else 0.95,
                resolver=self.name,
                method="exact" if exact_display else "synonym",
            )

        if not self.fuzzy:
            return None

        matches = process.extract(key, self._keys, scorer=fuzz.token_set_ratio, limit=3)
        if not matches:
            return None
        best_key, best_score, _ = matches[0]
        if best_score < self.fuzzy_threshold:
            return None

        entry = self._index[best_key]
        return Resolution(
            text=text,
            coding=entry.to_coding(),
            score=round(best_score / 100.0, 4),
            resolver=self.name,
            method="fuzzy",
            candidates=tuple((m[0], round(m[1] / 100.0, 4)) for m in matches[1:]),
        )

    def known_codes(self) -> set[tuple[str, str]]:
        """Every ``(system, code)`` in this value set."""
        return {(e.system, e.code) for e in self.entries}

from_csv classmethod

from_csv(
    path: str | Path,
    *,
    name: str | None = None,
    **kwargs: Any,
) -> LocalValueSet

Load from a CSV with system,code,display,synonyms.

synonyms is pipe-separated, as SPEC §6.3 specifies.

Source code in src/fhirground/terminology/local.py
@classmethod
def from_csv(cls, path: str | Path, *, name: str | None = None, **kwargs: Any) -> LocalValueSet:
    """Load from a CSV with ``system,code,display,synonyms``.

    ``synonyms`` is pipe-separated, as SPEC §6.3 specifies.
    """
    path = Path(path)
    if not path.exists():
        raise TerminologyError(f"value set file not found: {path}")

    entries: list[ValueSetEntry] = []
    with path.open(encoding="utf-8-sig", newline="") as fh:
        reader = csv.DictReader(fh)
        if reader.fieldnames is None:
            raise TerminologyError(f"value set {path} has no header row")
        missing = [c for c in REQUIRED_COLUMNS if c not in reader.fieldnames]
        if missing:
            raise TerminologyError(
                f"value set {path} is missing column(s) {missing}; "
                f"required: {list(REQUIRED_COLUMNS)}, found: {reader.fieldnames}"
            )
        for lineno, row in enumerate(reader, start=2):
            system = (row.get("system") or "").strip()
            code = (row.get("code") or "").strip()
            display = (row.get("display") or "").strip()
            if not (system and code and display):
                raise TerminologyError(
                    f"{path}:{lineno}: system, code, and display are all required"
                )
            raw_syn = (row.get("synonyms") or "").strip()
            synonyms = tuple(s.strip() for s in raw_syn.split("|") if s.strip())
            entries.append(
                ValueSetEntry(system=system, code=code, display=display, synonyms=synonyms)
            )
    return cls(entries, name=name or f"local:{path.stem}", **kwargs)

from_json classmethod

from_json(
    path: str | Path,
    *,
    name: str | None = None,
    **kwargs: Any,
) -> LocalValueSet

Load from a JSON list of {system, code, display, synonyms}.

Source code in src/fhirground/terminology/local.py
@classmethod
def from_json(
    cls, path: str | Path, *, name: str | None = None, **kwargs: Any
) -> LocalValueSet:
    """Load from a JSON list of ``{system, code, display, synonyms}``."""
    path = Path(path)
    if not path.exists():
        raise TerminologyError(f"value set file not found: {path}")
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise TerminologyError(f"{path}: malformed JSON: {exc.msg}") from exc
    if not isinstance(data, list):
        raise TerminologyError(f"{path}: expected a JSON array of concepts")

    entries = []
    for i, row in enumerate(data):
        if not isinstance(row, dict):
            raise TerminologyError(f"{path}: entry {i} is not an object")
        missing = [c for c in REQUIRED_COLUMNS if not row.get(c)]
        if missing:
            raise TerminologyError(f"{path}: entry {i} is missing {missing}")
        synonyms = row.get("synonyms") or []
        if isinstance(synonyms, str):
            synonyms = [s.strip() for s in synonyms.split("|") if s.strip()]
        entries.append(
            ValueSetEntry(
                system=str(row["system"]),
                code=str(row["code"]),
                display=str(row["display"]),
                synonyms=tuple(str(s) for s in synonyms),
            )
        )
    return cls(entries, name=name or f"local:{path.stem}", **kwargs)

from_entries classmethod

from_entries(
    rows: list[dict[str, Any]],
    *,
    name: str = "local",
    **kwargs: Any,
) -> LocalValueSet

Build from plain dicts, for tests and programmatic use.

Source code in src/fhirground/terminology/local.py
@classmethod
def from_entries(
    cls, rows: list[dict[str, Any]], *, name: str = "local", **kwargs: Any
) -> LocalValueSet:
    """Build from plain dicts, for tests and programmatic use."""
    entries = []
    for row in rows:
        synonyms = row.get("synonyms") or ()
        if isinstance(synonyms, str):
            synonyms = tuple(s.strip() for s in synonyms.split("|") if s.strip())
        entries.append(
            ValueSetEntry(
                system=str(row["system"]),
                code=str(row["code"]),
                display=str(row["display"]),
                synonyms=tuple(synonyms),
            )
        )
    return cls(entries, name=name, **kwargs)

resolve

resolve(
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None

Resolve text against this value set.

Returns:

Type Description
Resolution | None

A coded :class:Resolution on a hit, or None so a chain can try

Resolution | None

the next resolver. Scores: 1.0 for an exact display match, 0.95 for

Resolution | None

an exact synonym match, and ratio/100 for a fuzzy hit.

Source code in src/fhirground/terminology/local.py
def resolve(
    self,
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None:
    """Resolve text against this value set.

    Returns:
        A coded :class:`Resolution` on a hit, or None so a chain can try
        the next resolver. Scores: 1.0 for an exact display match, 0.95 for
        an exact synonym match, and ``ratio/100`` for a fuzzy hit.
    """
    _ = mention_type, context
    key = _normalize(text or "")
    if not key:
        return None

    entry = self._index.get(key)
    if entry is not None:
        exact_display = _normalize(entry.display) == key
        return Resolution(
            text=text,
            coding=entry.to_coding(),
            score=1.0 if exact_display else 0.95,
            resolver=self.name,
            method="exact" if exact_display else "synonym",
        )

    if not self.fuzzy:
        return None

    matches = process.extract(key, self._keys, scorer=fuzz.token_set_ratio, limit=3)
    if not matches:
        return None
    best_key, best_score, _ = matches[0]
    if best_score < self.fuzzy_threshold:
        return None

    entry = self._index[best_key]
    return Resolution(
        text=text,
        coding=entry.to_coding(),
        score=round(best_score / 100.0, 4),
        resolver=self.name,
        method="fuzzy",
        candidates=tuple((m[0], round(m[1] / 100.0, 4)) for m in matches[1:]),
    )

known_codes

known_codes() -> set[tuple[str, str]]

Every (system, code) in this value set.

Source code in src/fhirground/terminology/local.py
def known_codes(self) -> set[tuple[str, str]]:
    """Every ``(system, code)`` in this value set."""
    return {(e.system, e.code) for e in self.entries}

NullResolver

A resolver that never resolves anything.

Not a placeholder: it is the correct choice when no licensed terminology is available. Every resource becomes a text-only CodeableConcept, the terminology confidence component is absent rather than zero, and the output is honest about carrying no codes.

Source code in src/fhirground/terminology/local.py
class NullResolver:
    """A resolver that never resolves anything.

    Not a placeholder: it is the correct choice when no licensed terminology is
    available. Every resource becomes a text-only ``CodeableConcept``, the
    terminology confidence component is absent rather than zero, and the output
    is honest about carrying no codes.
    """

    name = "null"

    def resolve(
        self,
        text: str,
        mention_type: MentionType,
        context: dict[str, Any] | None = None,
    ) -> Resolution | None:
        """Always returns None, so the mention stays text-only."""
        _ = text, mention_type, context
        return None

    def known_codes(self) -> set[tuple[str, str]]:
        """Empty: this resolver can emit no codes at all."""
        return set()

resolve

resolve(
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None

Always returns None, so the mention stays text-only.

Source code in src/fhirground/terminology/local.py
def resolve(
    self,
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None:
    """Always returns None, so the mention stays text-only."""
    _ = text, mention_type, context
    return None

known_codes

known_codes() -> set[tuple[str, str]]

Empty: this resolver can emit no codes at all.

Source code in src/fhirground/terminology/local.py
def known_codes(self) -> set[tuple[str, str]]:
    """Empty: this resolver can emit no codes at all."""
    return set()

ValueSetEntry dataclass

One concept in a value set.

Source code in src/fhirground/terminology/local.py
@dataclass(frozen=True, slots=True)
class ValueSetEntry:
    """One concept in a value set."""

    system: str
    code: str
    display: str
    synonyms: tuple[str, ...] = field(default_factory=tuple)

    @property
    def surface_forms(self) -> tuple[str, ...]:
        """Display plus synonyms, in preference order."""
        return (self.display, *self.synonyms)

    def to_coding(self) -> Coding:
        """The code this entry represents."""
        return Coding(system=self.system, code=self.code, display=self.display)

surface_forms property

surface_forms: tuple[str, ...]

Display plus synonyms, in preference order.

to_coding

to_coding() -> Coding

The code this entry represents.

Source code in src/fhirground/terminology/local.py
def to_coding(self) -> Coding:
    """The code this entry represents."""
    return Coding(system=self.system, code=self.code, display=self.display)

fhirground.terminology.chain

Chaining resolvers: try each in turn, keep the first hit.

The practical arrangement is a local value set first and a network resolver second. Local is fast, deterministic, offline, and governed by whatever terminology the site is licensed for; the network is a fallback for the long tail. Putting them the other way round would make every run depend on a remote service and make results irreproducible.

A chain can also be configured to keep the best hit rather than the first, for comparing resolvers.

Chain

Several resolvers tried in order.

Parameters:

Name Type Description Default
resolvers list[TerminologyResolver]

Resolvers in priority order.

required
name str | None

Name recorded on resolutions and in the run summary.

None
strategy str

first keeps the first hit (the default, and fastest); best queries every resolver and keeps the highest score.

'first'
min_score float

A hit below this score is treated as a miss and the chain continues. Useful when a local value set returns weak fuzzy matches that a remote lookup would beat.

0.0
Source code in src/fhirground/terminology/chain.py
class Chain:
    """Several resolvers tried in order.

    Args:
        resolvers: Resolvers in priority order.
        name: Name recorded on resolutions and in the run summary.
        strategy: ``first`` keeps the first hit (the default, and fastest);
            ``best`` queries every resolver and keeps the highest score.
        min_score: A hit below this score is treated as a miss and the chain
            continues. Useful when a local value set returns weak fuzzy
            matches that a remote lookup would beat.
    """

    def __init__(
        self,
        resolvers: list[TerminologyResolver],
        *,
        name: str | None = None,
        strategy: str = "first",
        min_score: float = 0.0,
    ) -> None:
        if not resolvers:
            raise TerminologyError(
                "a Chain needs at least one resolver; use NullResolver for text-only output"
            )
        if strategy not in ("first", "best"):
            raise TerminologyError(f"unknown chain strategy {strategy!r}; use 'first' or 'best'")
        self.resolvers = resolvers
        self.strategy = strategy
        self.min_score = min_score
        self.name = name or "chain(" + "+".join(r.name for r in resolvers) + ")"

    def __len__(self) -> int:
        return len(self.resolvers)

    def resolve(
        self,
        text: str,
        mention_type: MentionType,
        context: dict[str, Any] | None = None,
    ) -> Resolution | None:
        """Resolve through the chain.

        Returns:
            The chosen :class:`Resolution` with its originating resolver
            recorded, or None when every resolver missed.
        """
        best: Resolution | None = None
        for resolver in self.resolvers:
            found = resolver.resolve(text, mention_type, context)
            if found is None or not found.is_coded:
                continue
            if found.score < self.min_score:
                continue
            if self.strategy == "first":
                return found
            if best is None or found.score > best.score:
                best = found
        return best

    def known_codes(self) -> set[tuple[str, str]]:
        """Union of every code any resolver in the chain could emit."""
        out: set[tuple[str, str]] = set()
        for resolver in self.resolvers:
            out |= resolver.known_codes()
        return out

resolve

resolve(
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None

Resolve through the chain.

Returns:

Type Description
Resolution | None

The chosen :class:Resolution with its originating resolver

Resolution | None

recorded, or None when every resolver missed.

Source code in src/fhirground/terminology/chain.py
def resolve(
    self,
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None:
    """Resolve through the chain.

    Returns:
        The chosen :class:`Resolution` with its originating resolver
        recorded, or None when every resolver missed.
    """
    best: Resolution | None = None
    for resolver in self.resolvers:
        found = resolver.resolve(text, mention_type, context)
        if found is None or not found.is_coded:
            continue
        if found.score < self.min_score:
            continue
        if self.strategy == "first":
            return found
        if best is None or found.score > best.score:
            best = found
    return best

known_codes

known_codes() -> set[tuple[str, str]]

Union of every code any resolver in the chain could emit.

Source code in src/fhirground/terminology/chain.py
def known_codes(self) -> set[tuple[str, str]]:
    """Union of every code any resolver in the chain could emit."""
    out: set[tuple[str, str]] = set()
    for resolver in self.resolvers:
        out |= resolver.known_codes()
    return out

fhirground.terminology.rxnav

RxNav resolver for medications: optional, opt-in, cached.

Uses the NLM RxNav approximateTerm endpoint, which is a public service that needs no API key. It is off by default and must be constructed explicitly, because:

  • it makes network calls, so results depend on a remote service and are not reproducible across runs;
  • it sends medication text extracted from a clinical note to a third party. That text is a note fragment. Sites with a data-use agreement that forbids sending note content outside their boundary must not enable this.

The second point is why :class:RxNavResolver takes no default and the docs carry a warning. A cache is on by default so the same term is not sent twice.

RxNavResolver

Resolve medication text to an RxNorm code through NLM RxNav.

Parameters:

Name Type Description Default
base_url str

RxNav REST base.

DEFAULT_BASE_URL
cache_path str | Path | None

SQLite cache location. None disables caching, which means every lookup is a network call.

'.cache/rxnav.sqlite'
min_score float

Minimum RxNav approximate-match score to accept.

DEFAULT_MIN_SCORE
timeout float

Per-request timeout in seconds.

10.0
client Client | None

Inject an httpx.Client for testing. Tests use respx to mock transport, so no test here touches the network.

None
offline bool

When true, answer only from cache and never call out. Lets a cached corpus be re-run with no network at all.

False

Example::

resolver = RxNavResolver(cache_path=".cache/rxnav.sqlite")
resolver.resolve("metformin 500 mg", MentionType.MEDICATION)
Source code in src/fhirground/terminology/rxnav.py
class RxNavResolver:
    """Resolve medication text to an RxNorm code through NLM RxNav.

    Args:
        base_url: RxNav REST base.
        cache_path: SQLite cache location. None disables caching, which means
            every lookup is a network call.
        min_score: Minimum RxNav approximate-match score to accept.
        timeout: Per-request timeout in seconds.
        client: Inject an ``httpx.Client`` for testing. Tests use ``respx`` to
            mock transport, so no test here touches the network.
        offline: When true, answer only from cache and never call out. Lets a
            cached corpus be re-run with no network at all.

    Example::

        resolver = RxNavResolver(cache_path=".cache/rxnav.sqlite")
        resolver.resolve("metformin 500 mg", MentionType.MEDICATION)
    """

    name = "rxnav"

    def __init__(
        self,
        *,
        base_url: str = DEFAULT_BASE_URL,
        cache_path: str | Path | None = ".cache/rxnav.sqlite",
        min_score: float = DEFAULT_MIN_SCORE,
        timeout: float = 10.0,
        client: httpx.Client | None = None,
        offline: bool = False,
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.min_score = min_score
        self.timeout = timeout
        self.offline = offline
        self._client = client
        self._owns_client = client is None
        self._cache = _Cache(cache_path) if cache_path else None
        self._resolved: set[tuple[str, str]] = set()

    def _get_client(self) -> httpx.Client:
        if self._client is None:
            self._client = httpx.Client(timeout=self.timeout)
        return self._client

    def close(self) -> None:
        """Close the HTTP client if this resolver created it."""
        if self._client is not None and self._owns_client:
            self._client.close()
            self._client = None

    def __enter__(self) -> RxNavResolver:
        return self

    def __exit__(self, *exc: object) -> None:
        self.close()

    def _fetch(self, term: str) -> Any | None:
        """Fetch an approximate match, preferring the cache."""
        if self._cache is not None:
            cached = self._cache.get(term)
            if cached is not None:
                return cached
        if self.offline:
            return None

        url = f"{self.base_url}/approximateTerm.json"
        try:
            response = self._get_client().get(url, params={"term": term, "maxEntries": 3})
            response.raise_for_status()
            payload = response.json()
        except httpx.HTTPError as exc:
            raise TerminologyError(
                f"RxNav request failed for a medication term: {type(exc).__name__}. "
                "Set offline=True to run from cache only."
            ) from exc
        except json.JSONDecodeError as exc:
            raise TerminologyError(f"RxNav returned a non-JSON response: {exc.msg}") from exc

        if self._cache is not None:
            self._cache.put(term, payload)
        return payload

    def resolve(
        self,
        text: str,
        mention_type: MentionType,
        context: dict[str, Any] | None = None,
    ) -> Resolution | None:
        """Resolve medication text to an RxNorm code.

        Returns None for non-medication mentions: RxNorm has nothing to say
        about a condition, and querying it anyway would waste a call and risk a
        nonsense match.
        """
        _ = context
        if mention_type is not MentionType.MEDICATION:
            return None
        term = (text or "").strip()
        if not term:
            return None

        payload = self._fetch(term)
        if not payload:
            return None

        candidates = (payload.get("approximateGroup") or {}).get("candidate") or []
        if not candidates:
            return None

        scored: list[tuple[str, str, float]] = []
        for candidate in candidates:
            rxcui = str(candidate.get("rxcui") or "").strip()
            if not rxcui:
                continue
            try:
                score = float(candidate.get("score") or 0.0)
            except (TypeError, ValueError):
                score = 0.0
            scored.append((rxcui, str(candidate.get("name") or "").strip(), score))

        if not scored:
            return None
        scored.sort(key=lambda row: -row[2])
        rxcui, display, score = scored[0]
        if score < self.min_score:
            return None

        self._resolved.add((RXNORM_SYSTEM, rxcui))
        return Resolution(
            text=text,
            coding=Coding(system=RXNORM_SYSTEM, code=rxcui, display=display or None),
            score=round(min(score, 100.0) / 100.0, 4),
            resolver=self.name,
            method="remote",
            candidates=tuple((name or code, round(s / 100.0, 4)) for code, name, s in scored[1:]),
        )

    def known_codes(self) -> set[tuple[str, str]]:
        """Codes this resolver has actually returned, plus anything cached.

        A remote resolver cannot enumerate its terminology in advance, so the
        no-invented-codes test treats remote-resolved codes as a separate,
        explicitly-allowed category rather than pretending this set is complete.
        """
        out = set(self._resolved)
        if self._cache is not None:
            for term in self._cache.terms():
                payload = self._cache.get(term) or {}
                for candidate in (payload.get("approximateGroup") or {}).get("candidate") or []:
                    rxcui = str(candidate.get("rxcui") or "").strip()
                    if rxcui:
                        out.add((RXNORM_SYSTEM, rxcui))
        return out

close

close() -> None

Close the HTTP client if this resolver created it.

Source code in src/fhirground/terminology/rxnav.py
def close(self) -> None:
    """Close the HTTP client if this resolver created it."""
    if self._client is not None and self._owns_client:
        self._client.close()
        self._client = None

resolve

resolve(
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None

Resolve medication text to an RxNorm code.

Returns None for non-medication mentions: RxNorm has nothing to say about a condition, and querying it anyway would waste a call and risk a nonsense match.

Source code in src/fhirground/terminology/rxnav.py
def resolve(
    self,
    text: str,
    mention_type: MentionType,
    context: dict[str, Any] | None = None,
) -> Resolution | None:
    """Resolve medication text to an RxNorm code.

    Returns None for non-medication mentions: RxNorm has nothing to say
    about a condition, and querying it anyway would waste a call and risk a
    nonsense match.
    """
    _ = context
    if mention_type is not MentionType.MEDICATION:
        return None
    term = (text or "").strip()
    if not term:
        return None

    payload = self._fetch(term)
    if not payload:
        return None

    candidates = (payload.get("approximateGroup") or {}).get("candidate") or []
    if not candidates:
        return None

    scored: list[tuple[str, str, float]] = []
    for candidate in candidates:
        rxcui = str(candidate.get("rxcui") or "").strip()
        if not rxcui:
            continue
        try:
            score = float(candidate.get("score") or 0.0)
        except (TypeError, ValueError):
            score = 0.0
        scored.append((rxcui, str(candidate.get("name") or "").strip(), score))

    if not scored:
        return None
    scored.sort(key=lambda row: -row[2])
    rxcui, display, score = scored[0]
    if score < self.min_score:
        return None

    self._resolved.add((RXNORM_SYSTEM, rxcui))
    return Resolution(
        text=text,
        coding=Coding(system=RXNORM_SYSTEM, code=rxcui, display=display or None),
        score=round(min(score, 100.0) / 100.0, 4),
        resolver=self.name,
        method="remote",
        candidates=tuple((name or code, round(s / 100.0, 4)) for code, name, s in scored[1:]),
    )

known_codes

known_codes() -> set[tuple[str, str]]

Codes this resolver has actually returned, plus anything cached.

A remote resolver cannot enumerate its terminology in advance, so the no-invented-codes test treats remote-resolved codes as a separate, explicitly-allowed category rather than pretending this set is complete.

Source code in src/fhirground/terminology/rxnav.py
def known_codes(self) -> set[tuple[str, str]]:
    """Codes this resolver has actually returned, plus anything cached.

    A remote resolver cannot enumerate its terminology in advance, so the
    no-invented-codes test treats remote-resolved codes as a separate,
    explicitly-allowed category rather than pretending this set is complete.
    """
    out = set(self._resolved)
    if self._cache is not None:
        for term in self._cache.terms():
            payload = self._cache.get(term) or {}
            for candidate in (payload.get("approximateGroup") or {}).get("candidate") or []:
                rxcui = str(candidate.get("rxcui") or "").strip()
                if rxcui:
                    out.add((RXNORM_SYSTEM, rxcui))
    return out

Deduplication

fhirground.dedup

Within-note deduplication.

Chunk overlap means the same sentence can be extracted twice, and a note may state the same finding in two places. Both produce duplicate mentions, and emitting two Conditions for one diagnosis would overstate what the note says.

Mentions merge when they agree on all three of:

  1. type -- a condition and an observation are never the same thing;
  2. normalized concept -- the resolved code when there is one, else the normalized text. Using the code when available is what lets "T2DM" and "type 2 diabetes" merge;
  3. assertion -- "possible pneumonia" and "pneumonia" are different claims and must not collapse into one.

Every evidence span survives the merge. A merged resource carries one evidence extension per source mention, so the audit trail does not shrink when the resource count does -- which is the difference between deduplication and data loss.

Cross-note reconciliation is explicitly out of scope: two notes mentioning the same diagnosis are two independent pieces of evidence, and merging them is a patient-level problem with its own failure modes.

MentionGroup dataclass

One deduplicated finding and every mention that supported it.

Attributes:

Name Type Description
key tuple[str, str, str]

The identity the group merged on.

mention Mention

The representative mention -- the one with the best grounding, so the emitted resource quotes the clearest evidence.

resolution Resolution

The representative resolution.

groundings list[Grounding]

Every evidence span, in document order.

members list[Mention]

Every mention in the group.

n_duplicates int

How many extra mentions merged in.

Source code in src/fhirground/dedup.py
@dataclass
class MentionGroup:
    """One deduplicated finding and every mention that supported it.

    Attributes:
        key: The identity the group merged on.
        mention: The representative mention -- the one with the best grounding,
            so the emitted resource quotes the clearest evidence.
        resolution: The representative resolution.
        groundings: Every evidence span, in document order.
        members: Every mention in the group.
        n_duplicates: How many extra mentions merged in.
    """

    key: tuple[str, str, str]
    mention: Mention
    resolution: Resolution
    groundings: list[Grounding] = field(default_factory=list)
    members: list[Mention] = field(default_factory=list)

    @property
    def n_duplicates(self) -> int:
        """Mentions beyond the first."""
        return max(0, len(self.members) - 1)

    @property
    def best_grounding(self) -> Grounding:
        """The highest-scoring span, used for the representative evidence."""
        return max(self.groundings, key=lambda g: (g.score, -g.start))

    def as_debug(self) -> dict[str, Any]:
        """Summary for the debug trace."""
        return {
            "key": list(self.key),
            "n_members": len(self.members),
            "n_duplicates": self.n_duplicates,
            "spans": [[g.start, g.end] for g in self.groundings],
            "strategies": [g.strategy.value for g in self.groundings],
        }

n_duplicates property

n_duplicates: int

Mentions beyond the first.

best_grounding property

best_grounding: Grounding

The highest-scoring span, used for the representative evidence.

as_debug

as_debug() -> dict[str, Any]

Summary for the debug trace.

Source code in src/fhirground/dedup.py
def as_debug(self) -> dict[str, Any]:
    """Summary for the debug trace."""
    return {
        "key": list(self.key),
        "n_members": len(self.members),
        "n_duplicates": self.n_duplicates,
        "spans": [[g.start, g.end] for g in self.groundings],
        "strategies": [g.strategy.value for g in self.groundings],
    }

dedup_mentions

dedup_mentions(
    items: list[tuple[Mention, Resolution, Grounding]],
) -> list[MentionGroup]

Group mentions that denote the same finding.

Parameters:

Name Type Description Default
items list[tuple[Mention, Resolution, Grounding]]

(mention, resolution, grounding) triples, in extraction order.

required

Returns:

Type Description
list[MentionGroup]

Groups in first-appearance order, each with every evidence span kept.

list[MentionGroup]

Order is stable so that resource ids are deterministic across runs.

Source code in src/fhirground/dedup.py
def dedup_mentions(
    items: list[tuple[Mention, Resolution, Grounding]],
) -> list[MentionGroup]:
    """Group mentions that denote the same finding.

    Args:
        items: ``(mention, resolution, grounding)`` triples, in extraction
            order.

    Returns:
        Groups in first-appearance order, each with every evidence span kept.
        Order is stable so that resource ids are deterministic across runs.
    """
    groups: dict[tuple[str, str, str], MentionGroup] = {}

    for mention, resolution, grounding in items:
        key = dedup_key(mention, resolution)
        existing = groups.get(key)
        if existing is None:
            groups[key] = MentionGroup(
                key=key,
                mention=mention,
                resolution=resolution,
                groundings=[grounding],
                members=[mention],
            )
            continue

        existing.members.append(mention)

        # Capture the incumbent's best score *before* adding the new span.
        # Appending first would put the new grounding inside the max, so it
        # could never beat it and the representative would never be promoted.
        incumbent_score = existing.best_grounding.score

        # Keep spans unique: overlap can yield the identical span twice, and
        # two identical evidence extensions add nothing.
        if not any(
            g.start == grounding.start and g.end == grounding.end for g in existing.groundings
        ):
            existing.groundings.append(grounding)

        # Promote the representative when the new mention is better grounded,
        # or when it carries detail the incumbent lacked. A mention with a dose
        # is more useful than the same mention without one.
        if grounding.score > incumbent_score or _detail_score(mention) > _detail_score(
            existing.mention
        ):
            existing.mention = mention
            if resolution.is_coded and not existing.resolution.is_coded:
                existing.resolution = resolution
        elif resolution.is_coded and not existing.resolution.is_coded:
            existing.resolution = resolution

    for group in groups.values():
        group.groundings.sort(key=lambda g: g.start)
    return list(groups.values())

dedup_key

dedup_key(
    mention: Mention, resolution: Resolution
) -> tuple[str, str, str]

The identity a mention merges on.

The concept part prefers the resolved code, because that is what makes different surface forms of one concept merge. Falling back to normalized text means unresolved mentions still deduplicate against themselves, just not against synonyms -- which is the correct, conservative outcome when no terminology was available to tell you they were the same.

Source code in src/fhirground/dedup.py
def dedup_key(mention: Mention, resolution: Resolution) -> tuple[str, str, str]:
    """The identity a mention merges on.

    The concept part prefers the resolved code, because that is what makes
    different surface forms of one concept merge. Falling back to normalized
    text means unresolved mentions still deduplicate against *themselves*,
    just not against synonyms -- which is the correct, conservative outcome
    when no terminology was available to tell you they were the same.
    """
    if resolution.coding is not None:
        concept = f"{resolution.coding.system}|{resolution.coding.code}"
    else:
        concept = f"text|{mention.normalized_text}"
    return (mention.mention_type.value, concept, mention.assertion.value)

matches_for_consistency

matches_for_consistency(
    target: tuple[Mention, Resolution],
    samples: list[list[tuple[Mention, Resolution]]],
) -> int

How many samples contain a mention matching target.

This is the self-consistency component of confidence (SPEC §4.6): with k samples at a non-zero temperature, a finding every sample agrees on is more trustworthy than one that appeared once.

Matching uses the same three-part identity as deduplication, so "consistent" means the same thing in both places.

Source code in src/fhirground/dedup.py
def matches_for_consistency(
    target: tuple[Mention, Resolution], samples: list[list[tuple[Mention, Resolution]]]
) -> int:
    """How many samples contain a mention matching ``target``.

    This is the self-consistency component of confidence (SPEC §4.6): with
    ``k`` samples at a non-zero temperature, a finding every sample agrees on
    is more trustworthy than one that appeared once.

    Matching uses the same three-part identity as deduplication, so
    "consistent" means the same thing in both places.
    """
    mention, resolution = target
    key = dedup_key(mention, resolution)
    count = 0
    for sample in samples:
        if any(dedup_key(m, r) == key for m, r in sample):
            count += 1
    return count

Mapping

fhirground.mapping.condition

Mention to FHIR R4B Condition.

Note the signature of :func:build_condition: it takes a :class:~fhirground.terminology.base.Resolution, not a code string. That is the structural half of the no-invented-codes rule -- a caller cannot pass a code that did not come from a resolver, because the parameter type will not accept one.

FHIR invariants, quoted verbatim from the R4 StructureDefinition and verified against it (see docs/decisions.md D-005):

  • con-3 (warning): "Condition.clinicalStatus SHALL be present if verificationStatus is not entered-in-error and category is problem-list-item". fhirground omits category by default, so the invariant does not bind and clinicalStatus may be absent. Note the polarity: the rule requires clinicalStatus when category is problem-list-item.
  • con-4 (error): "If condition is abated, then clinicalStatus must be either inactive, resolved, or remission". fhirground never sets abatement[x] in v1, so this is vacuously satisfied; the project rule checks it anyway.
  • con-5 (error): "Condition.clinicalStatus SHALL NOT be present if verification Status is entered-in-error" (the spacing typo is the spec's). fhirground never emits entered-in-error.

build_condition

build_condition(
    mention: Mention,
    resolution: Resolution,
    grounding: Grounding,
    decision: EmissionDecision,
    note: NoteInput,
    *,
    confidence: float,
    calibrated: bool = False,
    resource_id: str,
    include_quotes: bool = True,
    include_category: bool = False,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]

Build a Condition as a plain dict, ready for model validation.

Parameters:

Name Type Description Default
mention Mention

The source mention.

required
resolution Resolution

The resolved concept. A Resolution, never a code string -- this is what makes an invented code impossible.

required
grounding Grounding

Where the evidence sits in the note.

required
decision EmissionDecision

The assertion policy's verdict, which supplies verificationStatus.

required
note NoteInput

The source note, for subject and encounter.

required
confidence float

Score for the confidence extension.

required
calibrated bool

Whether the score came from a fitted calibrator.

False
resource_id str

Deterministic id assigned by the pipeline.

required
include_quotes bool

Carry the evidence quote in the resource.

True
include_category bool

Set category to problem-list-item. Off by default; turning it on makes con-3 bind, so the mapper then requires a clinicalStatus.

False
urls ExtensionUrls | None

Configured extension URLs.

None

Returns:

Type Description
dict[str, Any]

A Condition resource dict.

Raises:

Type Description
MappingError

If the decision is not to emit, or if the combination would violate con-3 or con-5.

Source code in src/fhirground/mapping/condition.py
def build_condition(
    mention: Mention,
    resolution: Resolution,
    grounding: Grounding,
    decision: EmissionDecision,
    note: NoteInput,
    *,
    confidence: float,
    calibrated: bool = False,
    resource_id: str,
    include_quotes: bool = True,
    include_category: bool = False,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]:
    """Build a ``Condition`` as a plain dict, ready for model validation.

    Args:
        mention: The source mention.
        resolution: The resolved concept. **A Resolution, never a code
            string** -- this is what makes an invented code impossible.
        grounding: Where the evidence sits in the note.
        decision: The assertion policy's verdict, which supplies
            ``verificationStatus``.
        note: The source note, for ``subject`` and ``encounter``.
        confidence: Score for the confidence extension.
        calibrated: Whether the score came from a fitted calibrator.
        resource_id: Deterministic id assigned by the pipeline.
        include_quotes: Carry the evidence quote in the resource.
        include_category: Set ``category`` to ``problem-list-item``. Off by
            default; turning it on makes con-3 bind, so the mapper then
            requires a ``clinicalStatus``.
        urls: Configured extension URLs.

    Returns:
        A ``Condition`` resource dict.

    Raises:
        MappingError: If the decision is not to emit, or if the combination
            would violate con-3 or con-5.
    """
    if not decision.emit:
        raise MappingError(
            f"build_condition called for a mention the policy dropped "
            f"({decision.reason.value if decision.reason else 'unknown'})"
        )
    if decision.verification_status is None:
        raise MappingError("a Condition needs a verificationStatus from the policy")

    u = urls or ExtensionUrls()
    ver_code, ver_display = _VERIFICATION_CODES[decision.verification_status]

    resource: dict[str, Any] = {
        "resourceType": "Condition",
        "id": resource_id,
        "subject": {"reference": note.patient_ref},
        "code": resolution.as_codeable_concept(),
        "verificationStatus": _status_concept(VERIFICATION_STATUS_SYSTEM, ver_code, ver_display),
    }

    if note.encounter_ref:
        resource["encounter"] = {"reference": note.encounter_ref}

    # clinicalStatus only from a hint, and only when the policy allows it.
    # con-5 forbids clinicalStatus beside entered-in-error; fhirground never
    # emits that status, and `refuted` carries no clinicalStatus either because
    # a refuted finding has no clinical course to describe.
    hint = mention.clinical_status_hint
    if decision.use_clinical_status_hint and hint is not None:
        code, display = _CLINICAL_STATUS_CODES[hint]
        resource["clinicalStatus"] = _status_concept(CLINICAL_STATUS_SYSTEM, code, display)

    if include_category:
        resource["category"] = [
            {
                "coding": [
                    {
                        "system": "http://terminology.hl7.org/CodeSystem/condition-category",
                        "code": "problem-list-item",
                        "display": "Problem List Item",
                    }
                ]
            }
        ]
        # con-3 binds once category is problem-list-item. Rather than emit a
        # resource that trips a spec warning, refuse and say why.
        if "clinicalStatus" not in resource and ver_code != "entered-in-error":
            raise MappingError(
                "include_category=True sets category to problem-list-item, which makes "
                "FHIR invariant con-3 require clinicalStatus, but this mention gave no "
                "clinical_status_hint. Either leave include_category off or supply a hint."
            )

    if mention.onset_text:
        resource["onsetString"] = mention.onset_text

    resource["extension"] = [
        confidence_extension(confidence, calibrated=calibrated, urls=u),
        evidence_extension(
            grounding,
            source_reference=note.source_reference,
            include_quote=include_quotes,
            urls=u,
        ),
    ]
    return resource

fhirground.mapping.medication_request

Mention to FHIR R4B MedicationRequest.

R4B keeps the R4 choice element medicationCodeableConcept. R5 replaced it with a single medication of type CodeableReference, which is why fhirground pins the R4B models rather than taking the library's default (see docs/decisions.md D-002).

authoredOn is set only from an explicitly resolved date, never inferred from the note timestamp. authoredOn is the date an order was written, and defaulting it to "when the note was typed" would fabricate a clinical fact that looks authoritative. An Observation's time can be inferred because a flag records that it was; an order date cannot.

build_medication_request

build_medication_request(
    mention: Mention,
    resolution: Resolution,
    grounding: Grounding,
    decision: EmissionDecision,
    note: NoteInput,
    *,
    confidence: float,
    calibrated: bool = False,
    resource_id: str,
    authored_on: ResolvedDate | None = None,
    include_quotes: bool = True,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]

Build a MedicationRequest as a plain dict.

Parameters:

Name Type Description Default
mention Mention

The source mention.

required
resolution Resolution

The resolved medication concept. A :class:~fhirground.terminology.base.Resolution, never a string.

required
grounding Grounding

Where the evidence sits in the note.

required
decision EmissionDecision

Policy verdict, supplying status.

required
note NoteInput

Source note, for subject and encounter.

required
confidence float

Score for the confidence extension.

required
calibrated bool

Whether a fitted calibrator produced the score.

False
resource_id str

Deterministic id from the pipeline.

required
authored_on ResolvedDate | None

An explicitly resolved date. Ignored when it is marked inferred, because authoredOn must not be guessed.

None
include_quotes bool

Carry the evidence quote.

True
urls ExtensionUrls | None

Configured extension URLs.

None

Returns:

Type Description
dict[str, Any]

A MedicationRequest resource dict.

Raises:

Type Description
MappingError

If the policy did not authorize emission.

Source code in src/fhirground/mapping/medication_request.py
def build_medication_request(
    mention: Mention,
    resolution: Resolution,
    grounding: Grounding,
    decision: EmissionDecision,
    note: NoteInput,
    *,
    confidence: float,
    calibrated: bool = False,
    resource_id: str,
    authored_on: ResolvedDate | None = None,
    include_quotes: bool = True,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]:
    """Build a ``MedicationRequest`` as a plain dict.

    Args:
        mention: The source mention.
        resolution: The resolved medication concept. A
            :class:`~fhirground.terminology.base.Resolution`, never a string.
        grounding: Where the evidence sits in the note.
        decision: Policy verdict, supplying ``status``.
        note: Source note, for ``subject`` and ``encounter``.
        confidence: Score for the confidence extension.
        calibrated: Whether a fitted calibrator produced the score.
        resource_id: Deterministic id from the pipeline.
        authored_on: An explicitly resolved date. Ignored when it is marked
            ``inferred``, because ``authoredOn`` must not be guessed.
        include_quotes: Carry the evidence quote.
        urls: Configured extension URLs.

    Returns:
        A ``MedicationRequest`` resource dict.

    Raises:
        MappingError: If the policy did not authorize emission.
    """
    if not decision.emit:
        raise MappingError(
            "build_medication_request called for a dropped mention "
            f"({decision.reason.value if decision.reason else 'unknown'})"
        )
    if decision.request_status is None:
        raise MappingError("a MedicationRequest needs a status from the policy")

    u = urls or ExtensionUrls()
    resource: dict[str, Any] = {
        "resourceType": "MedicationRequest",
        "id": resource_id,
        "status": _STATUS_VALUES[decision.request_status],
        "intent": DEFAULT_INTENT,
        "subject": {"reference": note.patient_ref},
        "medicationCodeableConcept": resolution.as_codeable_concept(),
    }

    if note.encounter_ref:
        resource["encounter"] = {"reference": note.encounter_ref}

    # Only an explicit date. `inferred` dates are rejected here on purpose.
    if authored_on is not None and not authored_on.inferred:
        resource["authoredOn"] = authored_on.to_fhir()

    dosage = _build_dosage(mention, grounding)
    if dosage:
        resource["dosageInstruction"] = [dosage]

    resource["extension"] = [
        confidence_extension(confidence, calibrated=calibrated, urls=u),
        evidence_extension(
            grounding,
            source_reference=note.source_reference,
            include_quote=include_quotes,
            urls=u,
        ),
    ]
    return resource

fhirground.mapping.observation

Mention to FHIR R4B Observation.

Two FHIR invariants apply, quoted verbatim from the R4 StructureDefinition:

  • obs-6 (error): "dataAbsentReason SHALL only be present if Observation.value[x] is not present". fhirground never sets dataAbsentReason, so this holds; the project rule checks it.
  • obs-7 (error): "If Observation.code is the same as an Observation.component.code then the value element associated with the code SHALL NOT be present". v1 emits no component, so this holds too.

The value rule that matters in practice: a number becomes valueQuantity only when a number was actually parsed. Everything else becomes valueString, and a blood pressure pair like 120/80 stays a string rather than being split into invented systolic and diastolic components.

build_observation

build_observation(
    mention: Mention,
    resolution: Resolution,
    grounding: Grounding,
    decision: EmissionDecision,
    note: NoteInput,
    *,
    confidence: float,
    calibrated: bool = False,
    resource_id: str,
    value: ParsedValue | None = None,
    effective: ResolvedDate | None = None,
    include_quotes: bool = True,
    mark_inferred_effective: bool = True,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]

Build an Observation as a plain dict.

Parameters:

Name Type Description Default
mention Mention

The source mention.

required
resolution Resolution

The resolved concept, as a :class:~fhirground.terminology.base.Resolution.

required
grounding Grounding

Where the evidence sits in the note.

required
decision EmissionDecision

Policy verdict.

required
note NoteInput

Source note.

required
confidence float

Score for the confidence extension.

required
calibrated bool

Whether a fitted calibrator produced the score.

False
resource_id str

Deterministic id from the pipeline.

required
value ParsedValue | None

Parsed value. When it carries a number, the resource gets a valueQuantity; otherwise a valueString.

None
effective ResolvedDate | None

Resolved date. When inferred, the resource carries the effective-inferred extension so a reader can tell that fhirground supplied the time.

None
include_quotes bool

Carry the evidence quote.

True
mark_inferred_effective bool

Add the inferred flag. Configurable because some consumers reject unknown extensions.

True
urls ExtensionUrls | None

Configured extension URLs.

None

Returns:

Type Description
dict[str, Any]

An Observation resource dict.

Raises:

Type Description
MappingError

If the policy did not authorize emission.

Source code in src/fhirground/mapping/observation.py
def build_observation(
    mention: Mention,
    resolution: Resolution,
    grounding: Grounding,
    decision: EmissionDecision,
    note: NoteInput,
    *,
    confidence: float,
    calibrated: bool = False,
    resource_id: str,
    value: ParsedValue | None = None,
    effective: ResolvedDate | None = None,
    include_quotes: bool = True,
    mark_inferred_effective: bool = True,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]:
    """Build an ``Observation`` as a plain dict.

    Args:
        mention: The source mention.
        resolution: The resolved concept, as a
            :class:`~fhirground.terminology.base.Resolution`.
        grounding: Where the evidence sits in the note.
        decision: Policy verdict.
        note: Source note.
        confidence: Score for the confidence extension.
        calibrated: Whether a fitted calibrator produced the score.
        resource_id: Deterministic id from the pipeline.
        value: Parsed value. When it carries a number, the resource gets a
            ``valueQuantity``; otherwise a ``valueString``.
        effective: Resolved date. When ``inferred``, the resource carries the
            ``effective-inferred`` extension so a reader can tell that
            fhirground supplied the time.
        include_quotes: Carry the evidence quote.
        mark_inferred_effective: Add the inferred flag. Configurable because
            some consumers reject unknown extensions.
        urls: Configured extension URLs.

    Returns:
        An ``Observation`` resource dict.

    Raises:
        MappingError: If the policy did not authorize emission.
    """
    if not decision.emit:
        raise MappingError(
            "build_observation called for a dropped mention "
            f"({decision.reason.value if decision.reason else 'unknown'})"
        )

    u = urls or ExtensionUrls()
    resource: dict[str, Any] = {
        "resourceType": "Observation",
        "id": resource_id,
        "status": DEFAULT_STATUS,
        "subject": {"reference": note.patient_ref},
        "code": resolution.as_codeable_concept(),
    }

    category = mention.obs_category
    if category is not None:
        resource["category"] = [
            {
                "coding": [
                    {
                        "system": CATEGORY_SYSTEM,
                        "code": category.value,
                        "display": _CATEGORY_DISPLAY[category],
                    }
                ]
            }
        ]

    if note.encounter_ref:
        resource["encounter"] = {"reference": note.encounter_ref}

    _apply_value(resource, mention, value)

    extensions: list[dict[str, Any]] = [
        confidence_extension(confidence, calibrated=calibrated, urls=u),
        evidence_extension(
            grounding,
            source_reference=note.source_reference,
            include_quote=include_quotes,
            urls=u,
        ),
    ]

    if effective is not None:
        resource["effectiveDateTime"] = effective.to_fhir()
        if effective.inferred and mark_inferred_effective:
            extensions.append(effective_inferred_extension(True, urls=u))

    resource["extension"] = extensions
    return resource

fhirground.mapping.provenance

One Provenance resource per note, linking outputs to their source.

This is what makes a Bundle auditable six months later. Without it, a reader has resources with evidence offsets but no record of which model, which prompt, and which code version produced them -- so a disagreement between two runs is impossible to explain.

Provenance.agent carries the model as a Device with a display string naming the model id and the package version. The FHIR Device is not a real resource in the Bundle: agent.who uses display only, because inventing a Device/<id> reference that resolves to nothing would be worse than a descriptive string.

build_provenance

build_provenance(
    *,
    resource_id: str,
    target_references: list[str],
    source_reference: str | None,
    patient_ref: str,
    model_id: str,
    prompt_version: str,
    package_version: str,
    fhir_library: str,
    schema_digest: str | None = None,
    recorded: datetime | None = None,
    backend_name: str | None = None,
    extra: dict[str, Any] | None = None,
) -> dict[str, Any]

Build the per-note Provenance.

Parameters:

Name Type Description Default
resource_id str

Deterministic id.

required
target_references list[str]

ResourceType/id for every resource this note produced. A Provenance with no targets is not emitted by the pipeline, since it would assert nothing.

required
source_reference str | None

The source DocumentReference, when known.

required
patient_ref str

Subject of the note, recorded so Provenance can be found by patient.

required
model_id str

The model that produced the mentions.

required
prompt_version str

Version string of the prompt template used.

required
package_version str

fhirground's version.

required
fhir_library str

The FHIR model library and version, e.g. fhir.resources 8.3.0 (R4B).

required
schema_digest str | None

Short hash of the mention schema the model decoded against, so two runs with different schemas are distinguishable.

None
recorded datetime | None

Timestamp. Defaults to now, in UTC.

None
backend_name str | None

Which backend ran, e.g. mock or bedrock.

None
extra dict[str, Any] | None

Additional key/value pairs to record as agent extensions.

None

Returns:

Type Description
dict[str, Any]

A Provenance resource dict.

Raises:

Type Description
ValueError

If there are no targets.

Source code in src/fhirground/mapping/provenance.py
def build_provenance(
    *,
    resource_id: str,
    target_references: list[str],
    source_reference: str | None,
    patient_ref: str,
    model_id: str,
    prompt_version: str,
    package_version: str,
    fhir_library: str,
    schema_digest: str | None = None,
    recorded: datetime | None = None,
    backend_name: str | None = None,
    extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build the per-note ``Provenance``.

    Args:
        resource_id: Deterministic id.
        target_references: ``ResourceType/id`` for every resource this note
            produced. A Provenance with no targets is not emitted by the
            pipeline, since it would assert nothing.
        source_reference: The source ``DocumentReference``, when known.
        patient_ref: Subject of the note, recorded so Provenance can be found
            by patient.
        model_id: The model that produced the mentions.
        prompt_version: Version string of the prompt template used.
        package_version: fhirground's version.
        fhir_library: The FHIR model library and version, e.g.
            ``fhir.resources 8.3.0 (R4B)``.
        schema_digest: Short hash of the mention schema the model decoded
            against, so two runs with different schemas are distinguishable.
        recorded: Timestamp. Defaults to now, in UTC.
        backend_name: Which backend ran, e.g. ``mock`` or ``bedrock``.
        extra: Additional key/value pairs to record as agent extensions.

    Returns:
        A ``Provenance`` resource dict.

    Raises:
        ValueError: If there are no targets.
    """
    if not target_references:
        raise ValueError(
            "a Provenance needs at least one target; a note that produced no "
            "resources should produce no Provenance either"
        )

    when = (recorded or datetime.now(UTC)).isoformat()

    agent_label_parts = [f"fhirground {package_version}"]
    if backend_name:
        agent_label_parts.append(f"backend={backend_name}")
    agent_label_parts.append(f"model={model_id}")
    agent_label_parts.append(f"prompt={prompt_version}")
    if schema_digest:
        agent_label_parts.append(f"schema={schema_digest}")
    agent_label_parts.append(fhir_library)

    resource: dict[str, Any] = {
        "resourceType": "Provenance",
        "id": resource_id,
        "target": [{"reference": ref} for ref in target_references],
        "recorded": when,
        "activity": {
            "coding": [{"system": ACTIVITY_SYSTEM, "code": "DERIVE", "display": "derive"}]
        },
        "agent": [
            {
                "type": {
                    "coding": [
                        {
                            "system": AGENT_TYPE_SYSTEM,
                            "code": "assembler",
                            "display": "Assembler",
                        }
                    ]
                },
                "who": {"display": " | ".join(agent_label_parts)},
            }
        ],
    }

    if source_reference:
        resource["entity"] = [{"role": "source", "what": {"reference": source_reference}}]

    if patient_ref:
        resource["agent"][0]["onBehalfOf"] = {"reference": patient_ref}

    if extra:
        resource["agent"][0]["extension"] = [
            {"url": f"urn:fhirground:run:{k}", "valueString": str(v)}
            for k, v in sorted(extra.items())
        ]

    return resource

build_bundle

build_bundle(
    resources: list[dict[str, Any]],
    *,
    bundle_id: str,
    timestamp: datetime | None = None,
) -> dict[str, Any]

Assemble resources into a collection Bundle.

collection rather than transaction because fhirground does not write to a server: a transaction Bundle would imply an intent to POST that v1 explicitly does not support.

Source code in src/fhirground/mapping/provenance.py
def build_bundle(
    resources: list[dict[str, Any]], *, bundle_id: str, timestamp: datetime | None = None
) -> dict[str, Any]:
    """Assemble resources into a ``collection`` Bundle.

    ``collection`` rather than ``transaction`` because fhirground does not
    write to a server: a transaction Bundle would imply an intent to POST that
    v1 explicitly does not support.
    """
    when = (timestamp or datetime.now(UTC)).isoformat()
    return {
        "resourceType": "Bundle",
        "id": bundle_id,
        "type": "collection",
        "timestamp": when,
        "entry": [
            {
                "fullUrl": f"urn:uuid:{r['resourceType']}-{r['id']}",
                "resource": r,
            }
            for r in resources
        ],
    }

fhirground.mapping.extensions

Extension URLs and builders.

Three extensions carry everything fhirground adds beyond plain FHIR:

  • extraction-confidence -- the score, and whether it was calibrated.
  • evidence -- where in the source note the claim came from.
  • effective-inferred -- that an Observation's time came from the note timestamp rather than from the note text.

The base URL is configurable and has no default that pretends to be real. Publishing resources with someone else's StructureDefinition URL would be worse than publishing a placeholder, so the placeholder is explicit and the docs tell you to set it.

The StructureDefinitions themselves are not shipped in v1; the URLs identify the extensions and the docs define their semantics.

ExtensionUrls dataclass

Resolved extension URLs for one configured base.

Source code in src/fhirground/mapping/extensions.py
@dataclass(frozen=True, slots=True)
class ExtensionUrls:
    """Resolved extension URLs for one configured base."""

    base: str = DEFAULT_EXTENSION_BASE

    def __post_init__(self) -> None:
        if not self.base.endswith("/"):
            object.__setattr__(self, "base", self.base + "/")

    @property
    def confidence(self) -> str:
        """URL of the ``extraction-confidence`` extension."""
        return f"{self.base}{CONFIDENCE_EXT}"

    @property
    def evidence(self) -> str:
        """URL of the ``evidence`` extension."""
        return f"{self.base}{EVIDENCE_EXT}"

    @property
    def effective_inferred(self) -> str:
        """URL of the ``effective-inferred`` extension."""
        return f"{self.base}{EFFECTIVE_INFERRED_EXT}"

    def all(self) -> tuple[str, ...]:
        """Every URL this configuration produces."""
        return (self.confidence, self.evidence, self.effective_inferred)

confidence property

confidence: str

URL of the extraction-confidence extension.

evidence property

evidence: str

URL of the evidence extension.

effective_inferred property

effective_inferred: str

URL of the effective-inferred extension.

all

all() -> tuple[str, ...]

Every URL this configuration produces.

Source code in src/fhirground/mapping/extensions.py
def all(self) -> tuple[str, ...]:
    """Every URL this configuration produces."""
    return (self.confidence, self.evidence, self.effective_inferred)

confidence_extension

confidence_extension(
    score: float,
    *,
    calibrated: bool = False,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]

Build the extraction-confidence extension.

Parameters:

Name Type Description Default
score float

The confidence in [0, 1].

required
calibrated bool

Whether a fitted calibrator produced it. This flag is the difference between a probability and a heuristic, so it is recorded on every resource rather than only in the run summary.

False
urls ExtensionUrls | None

Configured extension URLs.

None

Raises:

Type Description
ValueError

If the score is outside [0, 1], which would make the extension meaningless.

Source code in src/fhirground/mapping/extensions.py
def confidence_extension(
    score: float, *, calibrated: bool = False, urls: ExtensionUrls | None = None
) -> dict[str, Any]:
    """Build the ``extraction-confidence`` extension.

    Args:
        score: The confidence in [0, 1].
        calibrated: Whether a fitted calibrator produced it. **This flag is
            the difference between a probability and a heuristic**, so it is
            recorded on every resource rather than only in the run summary.
        urls: Configured extension URLs.

    Raises:
        ValueError: If the score is outside [0, 1], which would make the
            extension meaningless.
    """
    if not 0.0 <= score <= 1.0:
        raise ValueError(f"confidence must be in [0, 1], got {score}")
    u = urls or ExtensionUrls()
    return {
        "url": u.confidence,
        "valueDecimal": round(float(score), 4),
        "extension": [{"url": CALIBRATED_SUB, "valueBoolean": bool(calibrated)}],
    }

evidence_extension

evidence_extension(
    grounding: Grounding,
    *,
    source_reference: str | None = None,
    include_quote: bool = True,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]

Build one evidence extension from a grounding result.

Parameters:

Name Type Description Default
grounding Grounding

Where the claim came from.

required
source_reference str | None

Reference to the source DocumentReference.

None
include_quote bool

When False the quote is omitted for PHI minimization, but the offsets stay. SPEC §4.5 still requires offsets to be in range, so the evidence remains checkable against the note even when the text is not carried in the resource.

True
urls ExtensionUrls | None

Configured extension URLs.

None
Source code in src/fhirground/mapping/extensions.py
def evidence_extension(
    grounding: Grounding,
    *,
    source_reference: str | None = None,
    include_quote: bool = True,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]:
    """Build one ``evidence`` extension from a grounding result.

    Args:
        grounding: Where the claim came from.
        source_reference: Reference to the source ``DocumentReference``.
        include_quote: When False the quote is omitted for PHI minimization,
            but the offsets stay. SPEC §4.5 still requires offsets to be in
            range, so the evidence remains checkable against the note even
            when the text is not carried in the resource.
        urls: Configured extension URLs.
    """
    u = urls or ExtensionUrls()
    parts: list[dict[str, Any]] = []
    if source_reference:
        parts.append(
            {"url": EVIDENCE_SOURCE_SUB, "valueReference": {"reference": source_reference}}
        )
    parts.append({"url": EVIDENCE_START_SUB, "valueInteger": int(grounding.start)})
    parts.append({"url": EVIDENCE_END_SUB, "valueInteger": int(grounding.end)})
    if include_quote:
        parts.append({"url": EVIDENCE_QUOTE_SUB, "valueString": grounding.quote})
    parts.append({"url": EVIDENCE_GROUNDING_SUB, "valueCode": grounding.strategy.value})
    return {"url": u.evidence, "extension": parts}

effective_inferred_extension

effective_inferred_extension(
    inferred: bool = True,
    *,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]

Build the effective-inferred extension for an Observation.

Source code in src/fhirground/mapping/extensions.py
def effective_inferred_extension(
    inferred: bool = True, *, urls: ExtensionUrls | None = None
) -> dict[str, Any]:
    """Build the ``effective-inferred`` extension for an Observation."""
    u = urls or ExtensionUrls()
    return {"url": u.effective_inferred, "valueBoolean": bool(inferred)}

read_confidence

read_confidence(
    resource: dict[str, Any],
    urls: ExtensionUrls | None = None,
) -> float | None

Read the confidence back off a resource, or None if absent.

Source code in src/fhirground/mapping/extensions.py
def read_confidence(resource: dict[str, Any], urls: ExtensionUrls | None = None) -> float | None:
    """Read the confidence back off a resource, or None if absent."""
    u = urls or ExtensionUrls()
    for ext in resource.get("extension") or []:
        if ext.get("url") == u.confidence:
            value = ext.get("valueDecimal")
            return float(value) if value is not None else None
    return None

read_calibrated

read_calibrated(
    resource: dict[str, Any],
    urls: ExtensionUrls | None = None,
) -> bool | None

Whether the resource's confidence was calibrated, or None if absent.

Source code in src/fhirground/mapping/extensions.py
def read_calibrated(resource: dict[str, Any], urls: ExtensionUrls | None = None) -> bool | None:
    """Whether the resource's confidence was calibrated, or None if absent."""
    u = urls or ExtensionUrls()
    for ext in resource.get("extension") or []:
        if ext.get("url") == u.confidence:
            for sub in ext.get("extension") or []:
                if sub.get("url") == CALIBRATED_SUB:
                    return bool(sub.get("valueBoolean"))
    return None

read_evidence

read_evidence(
    resource: dict[str, Any],
    urls: ExtensionUrls | None = None,
) -> list[dict[str, Any]]

Read every evidence extension off a resource as flat dicts.

Returns:

Type Description
list[dict[str, Any]]

One dict per evidence extension with start, end, and whichever

list[dict[str, Any]]

of quote, grounding, and source were present.

Source code in src/fhirground/mapping/extensions.py
def read_evidence(
    resource: dict[str, Any], urls: ExtensionUrls | None = None
) -> list[dict[str, Any]]:
    """Read every evidence extension off a resource as flat dicts.

    Returns:
        One dict per evidence extension with ``start``, ``end``, and whichever
        of ``quote``, ``grounding``, and ``source`` were present.
    """
    u = urls or ExtensionUrls()
    out: list[dict[str, Any]] = []
    for ext in resource.get("extension") or []:
        if ext.get("url") != u.evidence:
            continue
        flat: dict[str, Any] = {}
        for sub in ext.get("extension") or []:
            key = sub.get("url")
            if key == EVIDENCE_START_SUB:
                flat["start"] = sub.get("valueInteger")
            elif key == EVIDENCE_END_SUB:
                flat["end"] = sub.get("valueInteger")
            elif key == EVIDENCE_QUOTE_SUB:
                flat["quote"] = sub.get("valueString")
            elif key == EVIDENCE_GROUNDING_SUB:
                flat["grounding"] = sub.get("valueCode")
            elif key == EVIDENCE_SOURCE_SUB:
                flat["source"] = (sub.get("valueReference") or {}).get("reference")
        out.append(flat)
    return out

Validation

fhirground.validate

Validation: model parsing, project rules, and an optional HL7 validator hook.

Three layers, in increasing cost:

  1. Model parse -- every resource is parsed with the pinned FHIR R4B models. A resource that will not parse is a bug in fhirground, not a warning.
  2. Project rules (SPEC §4.5) -- the invariants FHIR itself does not state, plus the three R4 invariants that bind on the resources v1 emits. These are what make the output auditable rather than merely well-formed: that every evidence offset really indexes the note, that no code arrived without a resolver, that the UCUM system never appears beside a code fhirground did not resolve.
  3. HL7 FHIR Validator -- optional, run only when the user supplies the jar path. Not bundled: it is a large Java artifact with its own release cadence.

Every rule has a stable name so a failure is actionable, and every rule has positive and negative tests.

ValidationReport dataclass

The outcome of validating one or more resources.

Source code in src/fhirground/validate.py
@dataclass
class ValidationReport:
    """The outcome of validating one or more resources."""

    findings: list[Finding] = field(default_factory=list)

    @property
    def errors(self) -> list[Finding]:
        """Findings that block emission."""
        return [f for f in self.findings if f.severity is Severity.ERROR]

    @property
    def warnings(self) -> list[Finding]:
        """Findings that are reported but do not block."""
        return [f for f in self.findings if f.severity is Severity.WARNING]

    @property
    def ok(self) -> bool:
        """Whether there are no errors."""
        return not self.errors

    def add(
        self,
        rule: str,
        message: str,
        *,
        severity: Severity = Severity.ERROR,
        resource: dict[str, Any] | None = None,
    ) -> None:
        """Record a finding."""
        self.findings.append(
            Finding(
                rule=rule,
                severity=severity,
                message=message,
                resource_type=(resource or {}).get("resourceType"),
                resource_id=(resource or {}).get("id"),
            )
        )

    def extend(self, other: ValidationReport) -> None:
        """Merge another report in."""
        self.findings.extend(other.findings)

    def as_dict(self) -> dict[str, Any]:
        """JSON-safe summary."""
        return {
            "ok": self.ok,
            "n_errors": len(self.errors),
            "n_warnings": len(self.warnings),
            "findings": [
                {
                    "rule": f.rule,
                    "severity": f.severity.value,
                    "message": f.message,
                    "resource_type": f.resource_type,
                    "resource_id": f.resource_id,
                }
                for f in self.findings
            ],
        }

errors property

errors: list[Finding]

Findings that block emission.

warnings property

warnings: list[Finding]

Findings that are reported but do not block.

ok property

ok: bool

Whether there are no errors.

add

add(
    rule: str,
    message: str,
    *,
    severity: Severity = Severity.ERROR,
    resource: dict[str, Any] | None = None,
) -> None

Record a finding.

Source code in src/fhirground/validate.py
def add(
    self,
    rule: str,
    message: str,
    *,
    severity: Severity = Severity.ERROR,
    resource: dict[str, Any] | None = None,
) -> None:
    """Record a finding."""
    self.findings.append(
        Finding(
            rule=rule,
            severity=severity,
            message=message,
            resource_type=(resource or {}).get("resourceType"),
            resource_id=(resource or {}).get("id"),
        )
    )

extend

extend(other: ValidationReport) -> None

Merge another report in.

Source code in src/fhirground/validate.py
def extend(self, other: ValidationReport) -> None:
    """Merge another report in."""
    self.findings.extend(other.findings)

as_dict

as_dict() -> dict[str, Any]

JSON-safe summary.

Source code in src/fhirground/validate.py
def as_dict(self) -> dict[str, Any]:
    """JSON-safe summary."""
    return {
        "ok": self.ok,
        "n_errors": len(self.errors),
        "n_warnings": len(self.warnings),
        "findings": [
            {
                "rule": f.rule,
                "severity": f.severity.value,
                "message": f.message,
                "resource_type": f.resource_type,
                "resource_id": f.resource_id,
            }
            for f in self.findings
        ],
    }

Finding dataclass

One validation problem.

Source code in src/fhirground/validate.py
@dataclass(frozen=True, slots=True)
class Finding:
    """One validation problem."""

    rule: str
    severity: Severity
    message: str
    resource_type: str | None = None
    resource_id: str | None = None

    def __str__(self) -> str:
        where = f" [{self.resource_type}/{self.resource_id}]" if self.resource_id else ""
        return f"{self.severity.value}: {self.rule}: {self.message}{where}"

Severity

Bases: StrEnum

Whether a finding blocks emission.

error means the resource is dropped. warning means it is emitted and the finding is reported -- used for FHIR invariants the spec itself marks as warnings, such as con-3.

Source code in src/fhirground/validate.py
class Severity(StrEnum):
    """Whether a finding blocks emission.

    ``error`` means the resource is dropped. ``warning`` means it is emitted
    and the finding is reported -- used for FHIR invariants the spec itself
    marks as warnings, such as con-3.
    """

    ERROR = "error"
    WARNING = "warning"

validate_resource

validate_resource(
    resource: dict[str, Any],
    note_text: str | None = None,
    *,
    urls: ExtensionUrls | None = None,
    require_quote_match: bool = True,
) -> ValidationReport

Run the model parse and every project rule on one resource.

Source code in src/fhirground/validate.py
def validate_resource(
    resource: dict[str, Any],
    note_text: str | None = None,
    *,
    urls: ExtensionUrls | None = None,
    require_quote_match: bool = True,
) -> ValidationReport:
    """Run the model parse and every project rule on one resource."""
    report = ValidationReport()
    report.extend(parse_with_models(resource))
    report.extend(check_allowed_fields(resource))
    report.extend(check_extensions(resource, urls))
    report.extend(check_codings_have_system_and_code(resource))
    report.extend(check_ucum_usage(resource))
    report.extend(check_fhir_invariants(resource))
    if note_text is not None:
        report.extend(
            check_evidence_offsets(
                resource, note_text, urls=urls, require_quote_match=require_quote_match
            )
        )
    return report

validate_bundle

validate_bundle(
    bundle: dict[str, Any],
    note_text: str | None = None,
    *,
    urls: ExtensionUrls | None = None,
    require_quote_match: bool = True,
) -> ValidationReport

Validate a Bundle and every resource inside it.

Source code in src/fhirground/validate.py
def validate_bundle(
    bundle: dict[str, Any],
    note_text: str | None = None,
    *,
    urls: ExtensionUrls | None = None,
    require_quote_match: bool = True,
) -> ValidationReport:
    """Validate a Bundle and every resource inside it."""
    report = ValidationReport()
    report.extend(parse_with_models(bundle))
    for entry in bundle.get("entry") or []:
        resource = entry.get("resource") if isinstance(entry, dict) else None
        if isinstance(resource, dict):
            report.extend(
                validate_resource(
                    resource,
                    note_text,
                    urls=urls,
                    require_quote_match=require_quote_match,
                )
            )
    return report

parse_with_models

parse_with_models(
    resource: dict[str, Any],
) -> ValidationReport

Parse one resource with the pinned FHIR R4B models.

Source code in src/fhirground/validate.py
def parse_with_models(resource: dict[str, Any]) -> ValidationReport:
    """Parse one resource with the pinned FHIR R4B models."""
    report = ValidationReport()
    resource_type = resource.get("resourceType")
    if not resource_type:
        report.add("model-parse", "resource has no resourceType", resource=resource)
        return report

    model = _model_for(str(resource_type))
    if model is None:
        report.add(
            "model-parse",
            f"no R4B model is available for resourceType {resource_type!r}",
            resource=resource,
        )
        return report

    try:
        model.model_validate(resource)
    except Exception as exc:
        report.add(
            "model-parse",
            f"does not parse as FHIR R4B {resource_type}: {_compact(exc)}",
            resource=resource,
        )
    return report

check_extensions

check_extensions(
    resource: dict[str, Any],
    urls: ExtensionUrls | None = None,
) -> ValidationReport

Exactly one confidence extension and at least one evidence extension.

Source code in src/fhirground/validate.py
def check_extensions(
    resource: dict[str, Any], urls: ExtensionUrls | None = None
) -> ValidationReport:
    """Exactly one confidence extension and at least one evidence extension."""
    u = urls or ExtensionUrls()
    report = ValidationReport()
    if resource.get("resourceType") == "Provenance":
        return report

    extensions = resource.get("extension") or []
    n_conf = sum(1 for e in extensions if e.get("url") == u.confidence)
    n_evid = sum(1 for e in extensions if e.get("url") == u.evidence)

    if n_conf != 1:
        report.add(
            "exactly-one-confidence",
            f"expected exactly 1 extraction-confidence extension, found {n_conf}",
            resource=resource,
        )
    if n_evid < 1:
        report.add(
            "at-least-one-evidence",
            "every emitted resource must carry at least one evidence extension; "
            "an ungrounded resource is not auditable",
            resource=resource,
        )
    return report

check_evidence_offsets

check_evidence_offsets(
    resource: dict[str, Any],
    note_text: str,
    *,
    urls: ExtensionUrls | None = None,
    require_quote_match: bool = True,
) -> ValidationReport

Offsets index the note, and the quote matches what is there.

SPEC §4.5: note_text[start:end] normalized equals the stored quote normalized. When quotes are omitted for PHI minimization the offsets must still be in range -- so the claim stays checkable against the note even when the resource does not carry the text.

Source code in src/fhirground/validate.py
def check_evidence_offsets(
    resource: dict[str, Any],
    note_text: str,
    *,
    urls: ExtensionUrls | None = None,
    require_quote_match: bool = True,
) -> ValidationReport:
    """Offsets index the note, and the quote matches what is there.

    SPEC §4.5: ``note_text[start:end]`` normalized equals the stored quote
    normalized. When quotes are omitted for PHI minimization the offsets must
    still be in range -- so the claim stays checkable against the note even
    when the resource does not carry the text.
    """
    report = ValidationReport()
    for i, evidence in enumerate(read_evidence(resource, urls)):
        start, end = evidence.get("start"), evidence.get("end")
        if start is None or end is None:
            report.add(
                "evidence-offsets-present",
                f"evidence[{i}] is missing start or end",
                resource=resource,
            )
            continue
        if not (0 <= start <= end <= len(note_text)):
            report.add(
                "evidence-offsets-in-range",
                f"evidence[{i}] offsets [{start}:{end}] are outside the note "
                f"(length {len(note_text)})",
                resource=resource,
            )
            continue
        quote = evidence.get("quote")
        if quote is None:
            continue  # omitted by include_quotes=False; offsets already checked
        if require_quote_match:
            actual = " ".join(note_text[start:end].split()).lower()
            stored = " ".join(quote.split()).lower()
            if actual != stored:
                report.add(
                    "evidence-quote-matches-offsets",
                    f"evidence[{i}] quote does not match note_text[{start}:{end}]",
                    resource=resource,
                )
    return report

check_codings_have_system_and_code

check_codings_have_system_and_code(
    resource: dict[str, Any],
) -> ValidationReport

Every coding has a system and a code.

SPEC §4.5 also requires the display to have come from a Resolution. That half is enforced structurally -- the mapping functions accept only Resolution objects -- because no post-hoc inspection of a dict can tell where a string came from. This rule catches the observable part.

Source code in src/fhirground/validate.py
def check_codings_have_system_and_code(resource: dict[str, Any]) -> ValidationReport:
    """Every coding has a system and a code.

    SPEC §4.5 also requires the display to have come from a ``Resolution``.
    That half is enforced *structurally* -- the mapping functions accept only
    ``Resolution`` objects -- because no post-hoc inspection of a dict can
    tell where a string came from. This rule catches the observable part.
    """
    report = ValidationReport()
    for path, coding in _iter_codings(resource):
        if not coding.get("system"):
            report.add(
                "coding-has-system",
                f"coding at {path} has no system",
                resource=resource,
            )
        if not coding.get("code"):
            report.add("coding-has-code", f"coding at {path} has no code", resource=resource)
    return report

check_ucum_usage

check_ucum_usage(
    resource: dict[str, Any],
) -> ValidationReport

The UCUM system appears only beside a code from the bundled table.

Without this rule, a future change could emit http://unitsofmeasure.org beside a guessed code -- a hallucinated code wearing a standards URL, which is harder to spot than a plainly missing one.

Source code in src/fhirground/validate.py
def check_ucum_usage(resource: dict[str, Any]) -> ValidationReport:
    """The UCUM system appears only beside a code from the bundled table.

    Without this rule, a future change could emit ``http://unitsofmeasure.org``
    beside a guessed code -- a hallucinated code wearing a standards URL, which
    is harder to spot than a plainly missing one.
    """
    report = ValidationReport()
    for path, quantity in _iter_quantities(resource):
        system, code = quantity.get("system"), quantity.get("code")
        if system == UCUM_SYSTEM and not is_known_ucum_code(code):
            report.add(
                "ucum-code-from-table",
                f"{path} declares the UCUM system with code {code!r}, which is not in "
                "fhirground's unit table; an unrecognized unit must be carried as "
                "`unit` text with no system or code",
                resource=resource,
            )
        if code and not system:
            report.add(
                "quantity-code-needs-system",
                f"{path} has a code with no system",
                resource=resource,
            )
    return report

check_allowed_fields

check_allowed_fields(
    resource: dict[str, Any],
) -> ValidationReport

No field outside the type's allowed set.

Guards against pass-through: if model output ever leaked into a resource dict, it would show up here as an unexpected key.

Source code in src/fhirground/validate.py
def check_allowed_fields(resource: dict[str, Any]) -> ValidationReport:
    """No field outside the type's allowed set.

    Guards against pass-through: if model output ever leaked into a resource
    dict, it would show up here as an unexpected key.
    """
    report = ValidationReport()
    resource_type = str(resource.get("resourceType") or "")
    allowed = ALLOWED_FIELDS.get(resource_type)
    if allowed is None:
        if resource_type not in ALLOWED_RESOURCE_TYPES:
            report.add(
                "allowed-resource-type",
                f"resourceType {resource_type!r} is not one fhirground emits",
                resource=resource,
            )
        return report
    unexpected = sorted(set(resource) - allowed)
    if unexpected:
        report.add(
            "allowed-fields",
            f"{resource_type} carries unexpected field(s) {unexpected}",
            resource=resource,
        )
    return report

check_fhir_invariants

check_fhir_invariants(
    resource: dict[str, Any],
) -> ValidationReport

The R4 invariants that bind on the resources v1 emits.

Text quoted verbatim from the R4 StructureDefinitions, verified against them rather than recalled (docs/decisions.md D-005).

Source code in src/fhirground/validate.py
def check_fhir_invariants(resource: dict[str, Any]) -> ValidationReport:
    """The R4 invariants that bind on the resources v1 emits.

    Text quoted verbatim from the R4 StructureDefinitions, verified against
    them rather than recalled (``docs/decisions.md`` D-005).
    """
    report = ValidationReport()
    resource_type = resource.get("resourceType")

    if resource_type == "Condition":
        clinical = _status_codes(resource.get("clinicalStatus"))
        verification = _status_codes(resource.get("verificationStatus"))
        has_clinical = bool(clinical)
        entered_in_error = "entered-in-error" in verification
        categories = _category_codes(resource)

        # con-5 (error): "Condition.clinicalStatus SHALL NOT be present if
        # verification Status is entered-in-error"
        if entered_in_error and has_clinical:
            report.add(
                "con-5",
                "Condition.clinicalStatus SHALL NOT be present if verification Status "
                "is entered-in-error",
                resource=resource,
            )

        # con-4 (error): "If condition is abated, then clinicalStatus must be
        # either inactive, resolved, or remission"
        abated = any(k.startswith("abatement") for k in resource)
        if abated and not (clinical & CON4_ALLOWED):
            report.add(
                "con-4",
                "If condition is abated, then clinicalStatus must be either inactive, "
                f"resolved, or remission (found {sorted(clinical) or 'none'})",
                resource=resource,
            )

        # con-3 (warning): "Condition.clinicalStatus SHALL be present if
        # verificationStatus is not entered-in-error and category is
        # problem-list-item". Note the polarity: it binds only when category
        # *is* problem-list-item, which fhirground omits by default.
        if "problem-list-item" in categories and not entered_in_error and not has_clinical:
            report.add(
                "con-3",
                "Condition.clinicalStatus SHALL be present if verificationStatus is not "
                "entered-in-error and category is problem-list-item",
                severity=Severity.WARNING,
                resource=resource,
            )

    if resource_type == "Observation":
        has_value = any(k.startswith("value") for k in resource)

        # obs-6 (error): "dataAbsentReason SHALL only be present if
        # Observation.value[x] is not present"
        if resource.get("dataAbsentReason") is not None and has_value:
            report.add(
                "obs-6",
                "dataAbsentReason SHALL only be present if Observation.value[x] is not present",
                resource=resource,
            )

        # obs-7 (error): "If Observation.code is the same as an
        # Observation.component.code then the value element associated with the
        # code SHALL NOT be present"
        own = _coding_keys(resource.get("code"))
        for component in resource.get("component") or []:
            if has_value and own & _coding_keys(component.get("code")):
                report.add(
                    "obs-7",
                    "If Observation.code is the same as an Observation.component.code "
                    "then the value element associated with the code SHALL NOT be present",
                    resource=resource,
                )
                break

    return report

run_hl7_validator

run_hl7_validator(
    resources: list[dict[str, Any]],
    jar_path: str | Path,
    *,
    fhir_version: str = "4.0.1",
    java: str | None = None,
    timeout: float = 600.0,
) -> ValidationReport

Run the official HL7 FHIR Validator, if the user supplies the jar.

The jar is not bundled: it is a large Java artifact with its own release cadence and licence. This hook shells out to it.

Parameters:

Name Type Description Default
resources list[dict[str, Any]]

Resources to validate.

required
jar_path str | Path

Path to validator_cli.jar.

required
fhir_version str

Version to validate against. 4.0.1 is R4; fhirground emits R4B-modelled resources, which for these three types are field-identical to R4 (docs/decisions.md D-002).

'4.0.1'
java str | None

Java executable. Defaults to whatever is on PATH.

None
timeout float

Seconds before giving up.

600.0

Returns:

Type Description
ValidationReport

A report. If Java or the jar is missing, that is reported as a single

ValidationReport

finding rather than raised, so an optional hook cannot break a run.

Source code in src/fhirground/validate.py
def run_hl7_validator(
    resources: list[dict[str, Any]],
    jar_path: str | Path,
    *,
    fhir_version: str = "4.0.1",
    java: str | None = None,
    timeout: float = 600.0,
) -> ValidationReport:
    """Run the official HL7 FHIR Validator, if the user supplies the jar.

    The jar is **not bundled**: it is a large Java artifact with its own
    release cadence and licence. This hook shells out to it.

    Args:
        resources: Resources to validate.
        jar_path: Path to ``validator_cli.jar``.
        fhir_version: Version to validate against. ``4.0.1`` is R4; fhirground
            emits R4B-modelled resources, which for these three types are
            field-identical to R4 (``docs/decisions.md`` D-002).
        java: Java executable. Defaults to whatever is on PATH.
        timeout: Seconds before giving up.

    Returns:
        A report. If Java or the jar is missing, that is reported as a single
        finding rather than raised, so an optional hook cannot break a run.
    """
    report = ValidationReport()
    jar = Path(jar_path)
    if not jar.exists():
        report.add("hl7-validator", f"validator jar not found at {jar}")
        return report

    java_bin = java or shutil.which("java")
    if not java_bin:
        report.add(
            "hl7-validator",
            "no `java` on PATH, so the HL7 validator hook was skipped. Install a JRE "
            "or omit --hl7-validator.",
            severity=Severity.WARNING,
        )
        return report

    with tempfile.TemporaryDirectory(prefix="fhirground-hl7-") as tmp:
        tmpdir = Path(tmp)
        paths = []
        for i, resource in enumerate(resources):
            target = tmpdir / f"{resource.get('resourceType', 'Resource')}-{i}.json"
            target.write_text(json.dumps(resource))
            paths.append(str(target))

        cmd = [java_bin, "-jar", str(jar), *paths, "-version", fhir_version]
        try:
            completed = subprocess.run(
                cmd, capture_output=True, text=True, timeout=timeout, check=False
            )
        except (OSError, subprocess.SubprocessError) as exc:
            report.add("hl7-validator", f"could not run the validator: {exc}")
            return report

        output = f"{completed.stdout}\n{completed.stderr}"
        for line in output.splitlines():
            stripped = line.strip()
            lowered = stripped.lower()
            if lowered.startswith("error") or " error " in lowered[:40]:
                report.add("hl7-validator", stripped)
            elif lowered.startswith("warning"):
                report.add("hl7-validator", stripped, severity=Severity.WARNING)

        if completed.returncode != 0 and not report.errors:
            report.add(
                "hl7-validator",
                f"validator exited {completed.returncode} without a parseable error line",
            )
    return report

Confidence

fhirground.confidence

Confidence scoring and calibration.

An uncalibrated score is not a probability. It is a weighted mean of heuristics, and 0.8 does not mean "right 80% of the time". Every resource records whether its score was calibrated, the docs say this in the same words, and :class:Calibrator exists so the claim can be made true on labelled data.

Five components (SPEC §4.6), each in [0, 1] or absent:

=========== ====== ==================================================== component weight meaning =========== ====== ==================================================== g .35 grounding: 1.0 exact, 0.9 normalized, ratio * 0.8 fuzzy c .30 self-consistency across k samples t .20 the resolver's match score v .15 validation: 1.0 no repairs, 0.8 one, 0.6 two l .00 mean token probability, when the backend exposes it =========== ====== ====================================================

Weights are renormalized over the components that are actually available, which is the part that matters: with a NullResolver there is no t, and scoring it as 0 would punish every resource for a configuration choice rather than for anything about the extraction.

ConfidenceComponents dataclass

The per-mention components, before aggregation.

None means unavailable, which is different from 0.0 meaning bad. Keeping them apart is the whole reason this is a dataclass of optionals rather than a dict of floats.

Source code in src/fhirground/confidence.py
@dataclass(frozen=True, slots=True)
class ConfidenceComponents:
    """The per-mention components, before aggregation.

    ``None`` means *unavailable*, which is different from 0.0 meaning *bad*.
    Keeping them apart is the whole reason this is a dataclass of optionals
    rather than a dict of floats.
    """

    g: float | None = None
    c: float | None = None
    t: float | None = None
    v: float | None = None
    l: float | None = None  # noqa: E741 - the spec names this component `l`

    def available(self) -> dict[str, float]:
        """The components that have values."""
        return {
            k: v
            for k, v in (("g", self.g), ("c", self.c), ("t", self.t), ("v", self.v), ("l", self.l))
            if v is not None
        }

    def as_dict(self) -> dict[str, float | None]:
        """All five components, including the absent ones, for the debug trace."""
        return {"g": self.g, "c": self.c, "t": self.t, "v": self.v, "l": self.l}

available

available() -> dict[str, float]

The components that have values.

Source code in src/fhirground/confidence.py
def available(self) -> dict[str, float]:
    """The components that have values."""
    return {
        k: v
        for k, v in (("g", self.g), ("c", self.c), ("t", self.t), ("v", self.v), ("l", self.l))
        if v is not None
    }

as_dict

as_dict() -> dict[str, float | None]

All five components, including the absent ones, for the debug trace.

Source code in src/fhirground/confidence.py
def as_dict(self) -> dict[str, float | None]:
    """All five components, including the absent ones, for the debug trace."""
    return {"g": self.g, "c": self.c, "t": self.t, "v": self.v, "l": self.l}

Calibrator dataclass

Maps heuristic scores to calibrated probabilities.

Two methods, both saved as JSON, never pickle -- a pickled model is arbitrary code execution on load, which is not an acceptable thing to put in a health data pipeline.

  • isotonic -- a monotone step function. Flexible and needs no distributional assumption, but can overfit on small data.
  • platt -- a one-parameter logistic fit. Smoother and more robust when labelled data is scarce, which it usually is.

Attributes:

Name Type Description
method str

isotonic or platt.

thresholds list[float]

Isotonic x-values.

values list[float]

Isotonic y-values.

coef float | None

Platt slope.

intercept float | None

Platt intercept.

n_samples int

How much labelled data the fit used, recorded because a calibrator fitted on thirty examples deserves less trust than one fitted on three thousand.

Source code in src/fhirground/confidence.py
@dataclass
class Calibrator:
    """Maps heuristic scores to calibrated probabilities.

    Two methods, both saved as **JSON, never pickle** -- a pickled model is
    arbitrary code execution on load, which is not an acceptable thing to put
    in a health data pipeline.

    * ``isotonic`` -- a monotone step function. Flexible and needs no
      distributional assumption, but can overfit on small data.
    * ``platt`` -- a one-parameter logistic fit. Smoother and more robust when
      labelled data is scarce, which it usually is.

    Attributes:
        method: ``isotonic`` or ``platt``.
        thresholds: Isotonic x-values.
        values: Isotonic y-values.
        coef: Platt slope.
        intercept: Platt intercept.
        n_samples: How much labelled data the fit used, recorded because a
            calibrator fitted on thirty examples deserves less trust than one
            fitted on three thousand.
    """

    method: str = "isotonic"
    thresholds: list[float] = field(default_factory=list)
    values: list[float] = field(default_factory=list)
    coef: float | None = None
    intercept: float | None = None
    n_samples: int = 0
    fitted: bool = False

    def fit(
        self, scores: list[float], labels: list[int | bool], method: str | None = None
    ) -> Calibrator:
        """Fit on labelled dev data.

        Args:
            scores: Uncalibrated scores.
            labels: 1 for a correct resource, 0 otherwise.
            method: ``isotonic`` or ``platt``. Defaults to the instance's.

        Raises:
            CalibrationError: On mismatched lengths, too little data, or a
                single-class label set. One class carries no information about
                where the decision boundary is, so refusing beats returning a
                constant that looks like a probability.
        """
        chosen = (method or self.method).lower()
        if chosen not in ("isotonic", "platt"):
            raise CalibrationError(
                f"unknown calibration method {chosen!r}; use 'isotonic' or 'platt'"
            )
        if len(scores) != len(labels):
            raise CalibrationError(
                f"scores and labels differ in length ({len(scores)} vs {len(labels)})"
            )
        if len(scores) < 10:
            raise CalibrationError(
                f"need at least 10 labelled examples to fit a calibrator, got {len(scores)}"
            )
        ints = [int(bool(y)) for y in labels]
        if len(set(ints)) < 2:
            raise CalibrationError(
                "labels contain a single class, so a calibrator cannot be fitted. "
                "Calibration needs both correct and incorrect examples."
            )

        try:
            import numpy as np
        except ImportError as exc:  # pragma: no cover - extra is declared
            raise CalibrationError(
                "calibration needs the [calibrate] extra: pip install 'fhirground[calibrate]'"
            ) from exc

        x = np.asarray(scores, dtype=float)
        y = np.asarray(ints, dtype=float)

        if chosen == "isotonic":
            try:
                from sklearn.isotonic import IsotonicRegression
            except ImportError as exc:  # pragma: no cover
                raise CalibrationError(
                    "isotonic calibration needs scikit-learn: pip install 'fhirground[calibrate]'"
                ) from exc
            model = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0)
            model.fit(x, y)
            self.thresholds = [float(v) for v in model.X_thresholds_]
            self.values = [float(v) for v in model.y_thresholds_]
            self.coef = None
            self.intercept = None
        else:
            try:
                from sklearn.linear_model import LogisticRegression
            except ImportError as exc:  # pragma: no cover
                raise CalibrationError(
                    "Platt scaling needs scikit-learn: pip install 'fhirground[calibrate]'"
                ) from exc
            model = LogisticRegression(solver="lbfgs")
            model.fit(x.reshape(-1, 1), y)
            self.coef = float(model.coef_[0][0])
            self.intercept = float(model.intercept_[0])
            self.thresholds = []
            self.values = []

        self.method = chosen
        self.n_samples = len(scores)
        self.fitted = True
        return self

    def transform(self, score: float) -> float:
        """Map one score to a calibrated probability.

        Raises:
            CalibrationError: If the calibrator was never fitted. Returning
                the input unchanged would let a resource claim
                ``calibrated: true`` while carrying a raw heuristic.
        """
        if not self.fitted:
            raise CalibrationError("calibrator has not been fitted; call fit() or load() first")
        if self.method == "isotonic":
            return round(_interp(score, self.thresholds, self.values), 6)
        if self.coef is None or self.intercept is None:  # pragma: no cover
            raise CalibrationError("Platt calibrator is missing its parameters")
        z = self.coef * score + self.intercept
        return round(1.0 / (1.0 + math.exp(-z)), 6)

    def transform_many(self, scores: list[float]) -> list[float]:
        """Map a list of scores."""
        return [self.transform(s) for s in scores]

    # -- persistence ----------------------------------------------------

    def to_dict(self) -> dict[str, Any]:
        """JSON-safe representation."""
        return {
            "format": "fhirground-calibrator/1",
            "method": self.method,
            "thresholds": self.thresholds,
            "values": self.values,
            "coef": self.coef,
            "intercept": self.intercept,
            "n_samples": self.n_samples,
            "fitted": self.fitted,
        }

    def save(self, path: str | Path) -> Path:
        """Write as JSON. No pickle, by design."""
        target = Path(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(json.dumps(self.to_dict(), indent=2))
        return target

    @classmethod
    def load(cls, path: str | Path) -> Calibrator:
        """Load from JSON.

        Raises:
            CalibrationError: If the file is missing, malformed, or not a
                fhirground calibrator.
        """
        source = Path(path)
        if not source.exists():
            raise CalibrationError(f"calibrator file not found: {source}")
        try:
            data = json.loads(source.read_text())
        except json.JSONDecodeError as exc:
            raise CalibrationError(f"{source}: malformed JSON: {exc.msg}") from exc
        if not isinstance(data, dict) or "method" not in data:
            raise CalibrationError(f"{source} is not a fhirground calibrator file")
        return cls(
            method=str(data.get("method", "isotonic")),
            thresholds=[float(v) for v in data.get("thresholds") or []],
            values=[float(v) for v in data.get("values") or []],
            coef=None if data.get("coef") is None else float(data["coef"]),
            intercept=None if data.get("intercept") is None else float(data["intercept"]),
            n_samples=int(data.get("n_samples") or 0),
            fitted=bool(data.get("fitted", True)),
        )

fit

fit(
    scores: list[float],
    labels: list[int | bool],
    method: str | None = None,
) -> Calibrator

Fit on labelled dev data.

Parameters:

Name Type Description Default
scores list[float]

Uncalibrated scores.

required
labels list[int | bool]

1 for a correct resource, 0 otherwise.

required
method str | None

isotonic or platt. Defaults to the instance's.

None

Raises:

Type Description
CalibrationError

On mismatched lengths, too little data, or a single-class label set. One class carries no information about where the decision boundary is, so refusing beats returning a constant that looks like a probability.

Source code in src/fhirground/confidence.py
def fit(
    self, scores: list[float], labels: list[int | bool], method: str | None = None
) -> Calibrator:
    """Fit on labelled dev data.

    Args:
        scores: Uncalibrated scores.
        labels: 1 for a correct resource, 0 otherwise.
        method: ``isotonic`` or ``platt``. Defaults to the instance's.

    Raises:
        CalibrationError: On mismatched lengths, too little data, or a
            single-class label set. One class carries no information about
            where the decision boundary is, so refusing beats returning a
            constant that looks like a probability.
    """
    chosen = (method or self.method).lower()
    if chosen not in ("isotonic", "platt"):
        raise CalibrationError(
            f"unknown calibration method {chosen!r}; use 'isotonic' or 'platt'"
        )
    if len(scores) != len(labels):
        raise CalibrationError(
            f"scores and labels differ in length ({len(scores)} vs {len(labels)})"
        )
    if len(scores) < 10:
        raise CalibrationError(
            f"need at least 10 labelled examples to fit a calibrator, got {len(scores)}"
        )
    ints = [int(bool(y)) for y in labels]
    if len(set(ints)) < 2:
        raise CalibrationError(
            "labels contain a single class, so a calibrator cannot be fitted. "
            "Calibration needs both correct and incorrect examples."
        )

    try:
        import numpy as np
    except ImportError as exc:  # pragma: no cover - extra is declared
        raise CalibrationError(
            "calibration needs the [calibrate] extra: pip install 'fhirground[calibrate]'"
        ) from exc

    x = np.asarray(scores, dtype=float)
    y = np.asarray(ints, dtype=float)

    if chosen == "isotonic":
        try:
            from sklearn.isotonic import IsotonicRegression
        except ImportError as exc:  # pragma: no cover
            raise CalibrationError(
                "isotonic calibration needs scikit-learn: pip install 'fhirground[calibrate]'"
            ) from exc
        model = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0)
        model.fit(x, y)
        self.thresholds = [float(v) for v in model.X_thresholds_]
        self.values = [float(v) for v in model.y_thresholds_]
        self.coef = None
        self.intercept = None
    else:
        try:
            from sklearn.linear_model import LogisticRegression
        except ImportError as exc:  # pragma: no cover
            raise CalibrationError(
                "Platt scaling needs scikit-learn: pip install 'fhirground[calibrate]'"
            ) from exc
        model = LogisticRegression(solver="lbfgs")
        model.fit(x.reshape(-1, 1), y)
        self.coef = float(model.coef_[0][0])
        self.intercept = float(model.intercept_[0])
        self.thresholds = []
        self.values = []

    self.method = chosen
    self.n_samples = len(scores)
    self.fitted = True
    return self

transform

transform(score: float) -> float

Map one score to a calibrated probability.

Raises:

Type Description
CalibrationError

If the calibrator was never fitted. Returning the input unchanged would let a resource claim calibrated: true while carrying a raw heuristic.

Source code in src/fhirground/confidence.py
def transform(self, score: float) -> float:
    """Map one score to a calibrated probability.

    Raises:
        CalibrationError: If the calibrator was never fitted. Returning
            the input unchanged would let a resource claim
            ``calibrated: true`` while carrying a raw heuristic.
    """
    if not self.fitted:
        raise CalibrationError("calibrator has not been fitted; call fit() or load() first")
    if self.method == "isotonic":
        return round(_interp(score, self.thresholds, self.values), 6)
    if self.coef is None or self.intercept is None:  # pragma: no cover
        raise CalibrationError("Platt calibrator is missing its parameters")
    z = self.coef * score + self.intercept
    return round(1.0 / (1.0 + math.exp(-z)), 6)

transform_many

transform_many(scores: list[float]) -> list[float]

Map a list of scores.

Source code in src/fhirground/confidence.py
def transform_many(self, scores: list[float]) -> list[float]:
    """Map a list of scores."""
    return [self.transform(s) for s in scores]

to_dict

to_dict() -> dict[str, Any]

JSON-safe representation.

Source code in src/fhirground/confidence.py
def to_dict(self) -> dict[str, Any]:
    """JSON-safe representation."""
    return {
        "format": "fhirground-calibrator/1",
        "method": self.method,
        "thresholds": self.thresholds,
        "values": self.values,
        "coef": self.coef,
        "intercept": self.intercept,
        "n_samples": self.n_samples,
        "fitted": self.fitted,
    }

save

save(path: str | Path) -> Path

Write as JSON. No pickle, by design.

Source code in src/fhirground/confidence.py
def save(self, path: str | Path) -> Path:
    """Write as JSON. No pickle, by design."""
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(self.to_dict(), indent=2))
    return target

load classmethod

load(path: str | Path) -> Calibrator

Load from JSON.

Raises:

Type Description
CalibrationError

If the file is missing, malformed, or not a fhirground calibrator.

Source code in src/fhirground/confidence.py
@classmethod
def load(cls, path: str | Path) -> Calibrator:
    """Load from JSON.

    Raises:
        CalibrationError: If the file is missing, malformed, or not a
            fhirground calibrator.
    """
    source = Path(path)
    if not source.exists():
        raise CalibrationError(f"calibrator file not found: {source}")
    try:
        data = json.loads(source.read_text())
    except json.JSONDecodeError as exc:
        raise CalibrationError(f"{source}: malformed JSON: {exc.msg}") from exc
    if not isinstance(data, dict) or "method" not in data:
        raise CalibrationError(f"{source} is not a fhirground calibrator file")
    return cls(
        method=str(data.get("method", "isotonic")),
        thresholds=[float(v) for v in data.get("thresholds") or []],
        values=[float(v) for v in data.get("values") or []],
        coef=None if data.get("coef") is None else float(data["coef"]),
        intercept=None if data.get("intercept") is None else float(data["intercept"]),
        n_samples=int(data.get("n_samples") or 0),
        fitted=bool(data.get("fitted", True)),
    )

aggregate

aggregate(
    components: ConfidenceComponents,
    weights: dict[str, float] | None = None,
) -> float

Weighted mean over the available components, renormalized.

Returns:

Type Description
float

The score in [0, 1]. When no component is available, returns 0.0 --

float

a resource nobody could say anything about gets no confidence, which

float

min_confidence can then filter.

Raises:

Type Description
ValueError

If a weight is negative, or every available component has weight zero (which would make the score undefined rather than 0).

Source code in src/fhirground/confidence.py
def aggregate(components: ConfidenceComponents, weights: dict[str, float] | None = None) -> float:
    """Weighted mean over the available components, renormalized.

    Returns:
        The score in [0, 1]. When no component is available, returns 0.0 --
        a resource nobody could say anything about gets no confidence, which
        ``min_confidence`` can then filter.

    Raises:
        ValueError: If a weight is negative, or every available component has
            weight zero (which would make the score undefined rather than 0).
    """
    w = dict(weights or DEFAULT_WEIGHTS)
    if any(v < 0 for v in w.values()):
        raise ValueError(f"weights must be non-negative, got {w}")

    present = components.available()
    if not present:
        return 0.0

    total = sum(w.get(k, 0.0) for k in present)
    if total <= 0:
        raise ValueError(
            f"every available component {sorted(present)} has weight 0 under {w}, so the "
            "score would be undefined. Give at least one of them a positive weight."
        )
    return round(sum(present[k] * w.get(k, 0.0) for k in present) / total, 6)

validation_component

validation_component(repairs: int) -> float

Validation component from the number of repair attempts used.

Source code in src/fhirground/confidence.py
def validation_component(repairs: int) -> float:
    """Validation component from the number of repair attempts used."""
    if repairs < 0:
        raise ValueError(f"repairs cannot be negative, got {repairs}")
    return _REPAIR_SCORES[min(repairs, len(_REPAIR_SCORES) - 1)]

self_consistency

self_consistency(
    matches: int, samples: int
) -> float | None

Fraction of samples that produced a matching mention.

Returns None when samples <= 1: with one sample there is nothing to be consistent with, and reporting 1.0 would claim agreement that was never tested.

Source code in src/fhirground/confidence.py
def self_consistency(matches: int, samples: int) -> float | None:
    """Fraction of samples that produced a matching mention.

    Returns None when ``samples <= 1``: with one sample there is nothing to be
    consistent with, and reporting 1.0 would claim agreement that was never
    tested.
    """
    if samples <= 1:
        return None
    if matches < 0 or matches > samples:
        raise ValueError(f"matches ({matches}) must be in [0, {samples}]")
    return round(matches / samples, 6)

Output

fhirground.export

Outputs: Bundles, NDJSON, clinval predictions, debug traces, run summary.

Four formats because four audiences:

  • Bundles -- one JSON per note, for a FHIR consumer.
  • NDJSON per resource type -- bulk-data style, for loading into a store.
  • clinval predictions -- so the sibling validation harness can score this output with no translation step. The contract is label = "<ResourceType>:<code or text>".
  • debug JSONL -- one trace per mention, with grounding, resolution, confidence components, and the emitted id or drop reason. This is the file that makes a disappointing result diagnosable.

write_outputs

write_outputs(
    results: list[NoteResult],
    outdir: str | Path,
    *,
    formats: Iterable[str] = FORMATS,
    system_name: str = "fhirground",
    model_id: str = "",
    prompt_version: str = "",
    started: datetime | None = None,
    backend_description: dict[str, Any] | None = None,
    resolver_description: dict[str, str] | None = None,
    cost_per_1k: dict[str, float] | None = None,
    cache_stats: dict[str, int] | None = None,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]

Write every requested output format.

Returns:

Type Description
dict[str, Any]

A mapping of format name to the path or paths written.

Raises:

Type Description
ValueError

On an unknown format name, rather than silently writing nothing the caller asked for.

Source code in src/fhirground/export.py
def write_outputs(
    results: list[NoteResult],
    outdir: str | Path,
    *,
    formats: Iterable[str] = FORMATS,
    system_name: str = "fhirground",
    model_id: str = "",
    prompt_version: str = "",
    started: datetime | None = None,
    backend_description: dict[str, Any] | None = None,
    resolver_description: dict[str, str] | None = None,
    cost_per_1k: dict[str, float] | None = None,
    cache_stats: dict[str, int] | None = None,
    urls: ExtensionUrls | None = None,
) -> dict[str, Any]:
    """Write every requested output format.

    Returns:
        A mapping of format name to the path or paths written.

    Raises:
        ValueError: On an unknown format name, rather than silently writing
            nothing the caller asked for.
    """
    wanted = [f.strip() for f in formats if f and f.strip()]
    unknown = [f for f in wanted if f not in FORMATS]
    if unknown:
        raise ValueError(f"unknown output format(s) {unknown}; known: {list(FORMATS)}")

    target = Path(outdir)
    target.mkdir(parents=True, exist_ok=True)
    written: dict[str, Any] = {}

    if "bundle" in wanted:
        written["bundles"] = write_bundles(results, target)
    if "ndjson" in wanted:
        written["ndjson"] = write_ndjson(results, target)
    if "clinval" in wanted:
        written["clinval"] = write_clinval_predictions(
            results,
            target,
            system_name=system_name,
            model_id=model_id,
            prompt_version=prompt_version,
            urls=urls,
        )
    if "debug" in wanted:
        written["debug"] = write_debug(results, target)
    if "summary" in wanted:
        written["summary"] = write_summary(
            results,
            target,
            started=started,
            backend_description=backend_description,
            resolver_description=resolver_description,
            cost_per_1k=cost_per_1k,
            cache_stats=cache_stats,
        )
    return written

write_bundles

write_bundles(
    results: Iterable[NoteResult], outdir: str | Path
) -> list[Path]

One Bundle JSON per note, named by note id.

Source code in src/fhirground/export.py
def write_bundles(results: Iterable[NoteResult], outdir: str | Path) -> list[Path]:
    """One Bundle JSON per note, named by note id."""
    target = Path(outdir) / "bundles"
    target.mkdir(parents=True, exist_ok=True)
    written = []
    for result in results:
        if not result.bundle:
            continue
        safe = "".join(c if c.isalnum() or c in "-_." else "_" for c in result.note.note_id)
        written.append(_write_json(result.bundle, target / f"{safe}.json"))
    return written

write_ndjson

write_ndjson(
    results: Iterable[NoteResult], outdir: str | Path
) -> dict[str, Path]

One NDJSON file per resource type, bulk-data style.

A type with no resources still gets an empty file, so a consumer can tell "none found" from "the run did not produce this type".

Source code in src/fhirground/export.py
def write_ndjson(results: Iterable[NoteResult], outdir: str | Path) -> dict[str, Path]:
    """One NDJSON file per resource type, bulk-data style.

    A type with no resources still gets an **empty file**, so a consumer can
    tell "none found" from "the run did not produce this type".
    """
    target = Path(outdir) / "ndjson"
    target.mkdir(parents=True, exist_ok=True)

    buckets: dict[str, list[dict[str, Any]]] = {t: [] for t in NDJSON_TYPES}
    for result in results:
        for resource in result.resources:
            buckets.setdefault(str(resource.get("resourceType")), []).append(resource)

    out: dict[str, Path] = {}
    for resource_type, resources in buckets.items():
        path = target / f"{resource_type}.ndjson"
        with path.open("w", encoding="utf-8") as fh:
            for resource in resources:
                fh.write(json.dumps(resource, default=str))
                fh.write("\n")
        out[resource_type] = path
    return out

write_clinval_predictions

write_clinval_predictions(
    results: Iterable[NoteResult],
    outdir: str | Path,
    *,
    system_name: str = "fhirground",
    model_id: str = "",
    prompt_version: str = "",
    urls: ExtensionUrls | None = None,
) -> Path

Write clinval_predictions.jsonl.

Every emitted resource becomes one prediction record with value=true. Dropped mentions are not emitted as value=false: a drop means fhirground declined to assert the finding, which is not the same as asserting its absence, and clinval reads a missing record as unscored rather than as a negative. Materializing negatives needs the label universe, which only the study knows.

Source code in src/fhirground/export.py
def write_clinval_predictions(
    results: Iterable[NoteResult],
    outdir: str | Path,
    *,
    system_name: str = "fhirground",
    model_id: str = "",
    prompt_version: str = "",
    urls: ExtensionUrls | None = None,
) -> Path:
    """Write ``clinval_predictions.jsonl``.

    Every emitted resource becomes one prediction record with ``value=true``.
    Dropped mentions are **not** emitted as ``value=false``: a drop means
    fhirground declined to assert the finding, which is not the same as
    asserting its absence, and clinval reads a missing record as *unscored*
    rather than as a negative. Materializing negatives needs the label
    universe, which only the study knows.
    """
    target = Path(outdir)
    target.mkdir(parents=True, exist_ok=True)
    path = target / "clinval_predictions.jsonl"

    with path.open("w", encoding="utf-8") as fh:
        for result in results:
            note = result.note
            stats = result.stats
            run_meta: dict[str, Any] = {
                "model": model_id or "unknown",
                "prompt_version": prompt_version or "unknown",
                # One pipeline pass over a note produces every record for that
                # note, so they share a call id and clinval charges the cost
                # once rather than per label.
                "call_id": note.note_id,
            }
            if stats.get("tokens_in"):
                run_meta["tokens_in"] = int(stats["tokens_in"])
            if stats.get("tokens_out"):
                run_meta["tokens_out"] = int(stats["tokens_out"])
            if stats.get("latency_s"):
                run_meta["latency_s"] = float(stats["latency_s"])

            for resource in result.resources:
                if resource.get("resourceType") == "Provenance":
                    continue
                record: dict[str, Any] = {
                    "system": system_name,
                    "note_id": note.note_id,
                    "patient_id": note.patient_ref,
                    "label": clinval_label(resource),
                    "value": True,
                    "note_datetime": note.note_datetime.isoformat(),
                    "run": run_meta,
                }
                confidence = read_confidence(resource, urls)
                if confidence is not None:
                    record["confidence"] = confidence
                evidence = read_evidence(resource, urls)
                if evidence and evidence[0].get("start") is not None:
                    span: dict[str, Any] = {
                        "start": evidence[0]["start"],
                        "end": evidence[0]["end"],
                    }
                    if evidence[0].get("quote"):
                        span["text"] = evidence[0]["quote"]
                    record["span"] = span
                fh.write(json.dumps(record, default=str))
                fh.write("\n")
    return path

write_debug

write_debug(
    results: Iterable[NoteResult], outdir: str | Path
) -> Path

One debug trace per mention, as JSONL.

Source code in src/fhirground/export.py
def write_debug(results: Iterable[NoteResult], outdir: str | Path) -> Path:
    """One debug trace per mention, as JSONL."""
    target = Path(outdir)
    target.mkdir(parents=True, exist_ok=True)
    path = target / "debug.jsonl"
    with path.open("w", encoding="utf-8") as fh:
        for result in results:
            for trace in result.debug:
                row = trace.as_dict()
                row["note_id"] = result.note.note_id
                fh.write(json.dumps(row, default=str))
                fh.write("\n")
    return path

write_summary

write_summary(
    results: list[NoteResult],
    outdir: str | Path,
    *,
    started: datetime | None = None,
    backend_description: dict[str, Any] | None = None,
    resolver_description: dict[str, str] | None = None,
    cost_per_1k: dict[str, float] | None = None,
    cache_stats: dict[str, int] | None = None,
) -> Path

Write run_summary.json.

Source code in src/fhirground/export.py
def write_summary(
    results: list[NoteResult],
    outdir: str | Path,
    *,
    started: datetime | None = None,
    backend_description: dict[str, Any] | None = None,
    resolver_description: dict[str, str] | None = None,
    cost_per_1k: dict[str, float] | None = None,
    cache_stats: dict[str, int] | None = None,
) -> Path:
    """Write ``run_summary.json``."""
    summary = summarize(results, started=started)
    if backend_description:
        summary["backend"] = backend_description
    if resolver_description:
        summary["resolvers"] = resolver_description
    if cache_stats:
        summary["cache"] = cache_stats

    if cost_per_1k:
        tokens_in = summary.get("tokens_in") or 0
        tokens_out = summary.get("tokens_out") or 0
        if tokens_in or tokens_out:
            summary["cost_estimate"] = {
                "currency": "USD",
                "input_per_1k": cost_per_1k.get("input_per_1k", 0.0),
                "output_per_1k": cost_per_1k.get("output_per_1k", 0.0),
                "total": round(
                    tokens_in / 1000 * cost_per_1k.get("input_per_1k", 0.0)
                    + tokens_out / 1000 * cost_per_1k.get("output_per_1k", 0.0),
                    6,
                ),
            }
        else:
            summary["cost_estimate"] = {
                "status": "unknown",
                "reason": "the backend reported no token counts",
            }

    return _write_json(summary, Path(outdir) / "run_summary.json")

clinval_label

clinval_label(resource: dict[str, Any]) -> str

The clinval label for a resource: <ResourceType>:<code or text>.

The contract clinval expects. It treats the label as an opaque string and never splits it, so a colon in the code is safe.

Source code in src/fhirground/export.py
def clinval_label(resource: dict[str, Any]) -> str:
    """The clinval label for a resource: ``<ResourceType>:<code or text>``.

    The contract clinval expects. It treats the label as an opaque string and
    never splits it, so a colon in the code is safe.
    """
    resource_type = str(resource.get("resourceType"))
    concept = resource.get("code") or resource.get("medicationCodeableConcept") or {}
    codings = concept.get("coding") or []
    if codings and codings[0].get("code"):
        return f"{resource_type}:{codings[0]['code']}"
    text = (concept.get("text") or "").strip()
    normalized = " ".join(text.lower().split()) or "unknown"
    return f"{resource_type}:{normalized}"

Scoring

fhirground.evaluate

A resource-level scorer against gold FHIR.

For synthetic benchmarks, where gold resources were generated from the same source records the notes were rendered from. It answers "did we recover the record" rather than "was the text understood", and those are different questions -- for the second one, use clinval.

A match needs all of:

  1. the same resource type;
  2. the same code, or the same normalized text when neither side is coded;
  3. compatible status fields -- a refuted Condition does not match a confirmed one, which is the whole point of assertion handling;
  4. numeric values within tolerance (1% relative by default, exact for integers).

The report also includes drop-reason accounting: how many gold negatives were correctly dropped. A pipeline that drops everything scores perfect precision, so recall and the drop breakdown have to be read together.

MatchSpec dataclass

How strictly two resources must agree to count as the same.

Attributes:

Name Type Description
require_code bool

A coded gold resource must be matched by the same code. With this off, a text match is accepted, which measures concept recall rather than coding accuracy.

require_status bool

Status fields must agree.

numeric_tolerance float

Relative tolerance for a numeric value.

exact_integers bool

Integer-valued quantities must match exactly, because a heart rate of 72 and 73 are different observations however small the relative difference.

match_text_fallback bool

When neither side is coded, compare normalized text.

Source code in src/fhirground/evaluate.py
@dataclass(frozen=True, slots=True)
class MatchSpec:
    """How strictly two resources must agree to count as the same.

    Attributes:
        require_code: A coded gold resource must be matched by the same code.
            With this off, a text match is accepted, which measures concept
            recall rather than coding accuracy.
        require_status: Status fields must agree.
        numeric_tolerance: Relative tolerance for a numeric value.
        exact_integers: Integer-valued quantities must match exactly, because
            a heart rate of 72 and 73 are different observations however small
            the relative difference.
        match_text_fallback: When neither side is coded, compare normalized
            text.
    """

    require_code: bool = True
    require_status: bool = True
    numeric_tolerance: float = 0.01
    exact_integers: bool = True
    match_text_fallback: bool = True

ScoreReport dataclass

The full scoring result.

Source code in src/fhirground/evaluate.py
@dataclass
class ScoreReport:
    """The full scoring result."""

    per_type: dict[str, TypeScore] = field(default_factory=dict)
    unmatched_predicted: list[dict[str, Any]] = field(default_factory=list)
    unmatched_gold: list[dict[str, Any]] = field(default_factory=list)
    drop_reasons: dict[str, int] = field(default_factory=dict)
    spec: MatchSpec = field(default_factory=MatchSpec)

    @property
    def totals(self) -> TypeScore:
        """Micro-averaged counts across types."""
        total = TypeScore(resource_type="ALL")
        for score in self.per_type.values():
            total.tp += score.tp
            total.fp += score.fp
            total.fn += score.fn
        return total

    def as_dict(self) -> dict[str, Any]:
        """JSON-safe report, the shape written to ``score.json``."""
        return {
            "match_spec": {
                "require_code": self.spec.require_code,
                "require_status": self.spec.require_status,
                "numeric_tolerance": self.spec.numeric_tolerance,
                "exact_integers": self.spec.exact_integers,
                "match_text_fallback": self.spec.match_text_fallback,
            },
            "totals": self.totals.as_dict(),
            "per_type": {k: v.as_dict() for k, v in sorted(self.per_type.items())},
            "drop_reasons": self.drop_reasons,
            "n_unmatched_predicted": len(self.unmatched_predicted),
            "n_unmatched_gold": len(self.unmatched_gold),
            "caveat": (
                "Precision rises when the pipeline emits less, so read recall and "
                "drop_reasons alongside it. These numbers measure recovery of the "
                "source records a synthetic note was rendered from, not clinical "
                "accuracy."
            ),
        }

    def to_markdown(self, digits: int = 3) -> str:
        """Render as a Markdown table."""

        def fmt(value: float | None) -> str:
            return "n/a" if value is None else f"{value:.{digits}f}"

        lines = [
            "| resource type | gold | predicted | TP | FP | FN | precision | recall | F1 |",
            "| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
        ]
        for name in sorted(self.per_type):
            s = self.per_type[name]
            lines.append(
                f"| {name} | {s.tp + s.fn} | {s.tp + s.fp} | {s.tp} | {s.fp} | {s.fn} | "
                f"{fmt(s.precision)} | {fmt(s.recall)} | {fmt(s.f1)} |"
            )
        t = self.totals
        lines.append(
            f"| **all** | {t.tp + t.fn} | {t.tp + t.fp} | {t.tp} | {t.fp} | {t.fn} | "
            f"{fmt(t.precision)} | {fmt(t.recall)} | {fmt(t.f1)} |"
        )
        return "\n".join(lines)

totals property

totals: TypeScore

Micro-averaged counts across types.

as_dict

as_dict() -> dict[str, Any]

JSON-safe report, the shape written to score.json.

Source code in src/fhirground/evaluate.py
def as_dict(self) -> dict[str, Any]:
    """JSON-safe report, the shape written to ``score.json``."""
    return {
        "match_spec": {
            "require_code": self.spec.require_code,
            "require_status": self.spec.require_status,
            "numeric_tolerance": self.spec.numeric_tolerance,
            "exact_integers": self.spec.exact_integers,
            "match_text_fallback": self.spec.match_text_fallback,
        },
        "totals": self.totals.as_dict(),
        "per_type": {k: v.as_dict() for k, v in sorted(self.per_type.items())},
        "drop_reasons": self.drop_reasons,
        "n_unmatched_predicted": len(self.unmatched_predicted),
        "n_unmatched_gold": len(self.unmatched_gold),
        "caveat": (
            "Precision rises when the pipeline emits less, so read recall and "
            "drop_reasons alongside it. These numbers measure recovery of the "
            "source records a synthetic note was rendered from, not clinical "
            "accuracy."
        ),
    }

to_markdown

to_markdown(digits: int = 3) -> str

Render as a Markdown table.

Source code in src/fhirground/evaluate.py
def to_markdown(self, digits: int = 3) -> str:
    """Render as a Markdown table."""

    def fmt(value: float | None) -> str:
        return "n/a" if value is None else f"{value:.{digits}f}"

    lines = [
        "| resource type | gold | predicted | TP | FP | FN | precision | recall | F1 |",
        "| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
    ]
    for name in sorted(self.per_type):
        s = self.per_type[name]
        lines.append(
            f"| {name} | {s.tp + s.fn} | {s.tp + s.fp} | {s.tp} | {s.fp} | {s.fn} | "
            f"{fmt(s.precision)} | {fmt(s.recall)} | {fmt(s.f1)} |"
        )
    t = self.totals
    lines.append(
        f"| **all** | {t.tp + t.fn} | {t.tp + t.fp} | {t.tp} | {t.fp} | {t.fn} | "
        f"{fmt(t.precision)} | {fmt(t.recall)} | {fmt(t.f1)} |"
    )
    return "\n".join(lines)

TypeScore dataclass

Precision, recall, and F1 for one resource type.

Source code in src/fhirground/evaluate.py
@dataclass
class TypeScore:
    """Precision, recall, and F1 for one resource type."""

    resource_type: str
    tp: int = 0
    fp: int = 0
    fn: int = 0

    @property
    def precision(self) -> float | None:
        """TP / (TP + FP), or None when nothing was predicted."""
        denominator = self.tp + self.fp
        return self.tp / denominator if denominator else None

    @property
    def recall(self) -> float | None:
        """TP / (TP + FN), or None when there was no gold."""
        denominator = self.tp + self.fn
        return self.tp / denominator if denominator else None

    @property
    def f1(self) -> float | None:
        """Harmonic mean, or None when either side is undefined."""
        p, r = self.precision, self.recall
        if p is None or r is None or (p + r) == 0:
            return None
        return 2 * p * r / (p + r)

    def as_dict(self) -> dict[str, Any]:
        """JSON-safe row. Undefined metrics are ``null``, never 0."""
        return {
            "resource_type": self.resource_type,
            "tp": self.tp,
            "fp": self.fp,
            "fn": self.fn,
            "n_gold": self.tp + self.fn,
            "n_predicted": self.tp + self.fp,
            "precision": self.precision,
            "recall": self.recall,
            "f1": self.f1,
        }

precision property

precision: float | None

TP / (TP + FP), or None when nothing was predicted.

recall property

recall: float | None

TP / (TP + FN), or None when there was no gold.

f1 property

f1: float | None

Harmonic mean, or None when either side is undefined.

as_dict

as_dict() -> dict[str, Any]

JSON-safe row. Undefined metrics are null, never 0.

Source code in src/fhirground/evaluate.py
def as_dict(self) -> dict[str, Any]:
    """JSON-safe row. Undefined metrics are ``null``, never 0."""
    return {
        "resource_type": self.resource_type,
        "tp": self.tp,
        "fp": self.fp,
        "fn": self.fn,
        "n_gold": self.tp + self.fn,
        "n_predicted": self.tp + self.fp,
        "precision": self.precision,
        "recall": self.recall,
        "f1": self.f1,
    }

score_resources

score_resources(
    predicted: list[dict[str, Any]],
    gold: list[dict[str, Any]],
    match: MatchSpec | None = None,
    *,
    drop_reasons: dict[str, int] | None = None,
) -> ScoreReport

Score predicted resources against gold.

Matching is greedy and one-to-one: each gold resource is claimed by at most one prediction, so emitting a finding twice costs a false positive rather than earning two true positives.

Parameters:

Name Type Description Default
predicted list[dict[str, Any]]

Predicted resources. Provenance is ignored.

required
gold list[dict[str, Any]]

Gold resources.

required
match MatchSpec | None

Matching strictness.

None
drop_reasons dict[str, int] | None

Drop counts from the run, carried into the report so precision can be read alongside what was declined.

None

Returns:

Name Type Description
A ScoreReport

class:ScoreReport.

Source code in src/fhirground/evaluate.py
def score_resources(
    predicted: list[dict[str, Any]],
    gold: list[dict[str, Any]],
    match: MatchSpec | None = None,
    *,
    drop_reasons: dict[str, int] | None = None,
) -> ScoreReport:
    """Score predicted resources against gold.

    Matching is greedy and one-to-one: each gold resource is claimed by at
    most one prediction, so emitting a finding twice costs a false positive
    rather than earning two true positives.

    Args:
        predicted: Predicted resources. ``Provenance`` is ignored.
        gold: Gold resources.
        match: Matching strictness.
        drop_reasons: Drop counts from the run, carried into the report so
            precision can be read alongside what was declined.

    Returns:
        A :class:`ScoreReport`.
    """
    spec = match or MatchSpec()
    pred = [r for r in predicted if r.get("resourceType") != "Provenance"]
    gold_list = [r for r in gold if r.get("resourceType") != "Provenance"]

    report = ScoreReport(spec=spec, drop_reasons=dict(drop_reasons or {}))
    for resource_type in sorted({str(r.get("resourceType")) for r in pred + gold_list}):
        report.per_type[resource_type] = TypeScore(resource_type=resource_type)

    claimed: set[int] = set()
    for resource in pred:
        resource_type = str(resource.get("resourceType"))
        score = report.per_type[resource_type]
        hit = None
        for i, candidate in enumerate(gold_list):
            if i in claimed:
                continue
            if resources_match(resource, candidate, spec):
                hit = i
                break
        if hit is None:
            score.fp += 1
            report.unmatched_predicted.append(_brief(resource))
        else:
            claimed.add(hit)
            score.tp += 1

    for i, candidate in enumerate(gold_list):
        if i in claimed:
            continue
        resource_type = str(candidate.get("resourceType"))
        report.per_type[resource_type].fn += 1
        report.unmatched_gold.append(_brief(candidate))

    return report

resources_match

resources_match(
    predicted: dict[str, Any],
    gold: dict[str, Any],
    spec: MatchSpec | None = None,
) -> bool

Whether two resources denote the same finding under spec.

Source code in src/fhirground/evaluate.py
def resources_match(
    predicted: dict[str, Any], gold: dict[str, Any], spec: MatchSpec | None = None
) -> bool:
    """Whether two resources denote the same finding under ``spec``."""
    s = spec or MatchSpec()

    if predicted.get("resourceType") != gold.get("resourceType"):
        return False

    pred_codes, gold_codes = _codes(predicted), _codes(gold)
    if gold_codes and pred_codes:
        if not (pred_codes & gold_codes):
            return False
    elif s.require_code and gold_codes and not pred_codes:
        return False
    elif s.match_text_fallback:
        pt, gt = _text(predicted), _text(gold)
        if not pt or not gt or not (pt in gt or gt in pt):
            return False
    else:
        return False

    if s.require_status:
        pred_status, gold_status = _statuses(predicted), _statuses(gold)
        for field_name, gold_values in gold_status.items():
            if not gold_values:
                continue
            pred_values = pred_status.get(field_name, frozenset())
            if pred_values and not (pred_values & gold_values):
                return False

    pred_value, gold_value = _numeric(predicted), _numeric(gold)
    if gold_value is not None and pred_value is not None:
        if s.exact_integers and float(gold_value).is_integer():
            if pred_value != gold_value:
                return False
        else:
            scale = abs(gold_value) or 1.0
            if abs(pred_value - gold_value) / scale > s.numeric_tolerance:
                return False

    return True

read_resources

read_resources(path: str | Path) -> list[dict[str, Any]]

Read resources from NDJSON, a Bundle, a directory, or a JSON array.

Source code in src/fhirground/evaluate.py
def read_resources(path: str | Path) -> list[dict[str, Any]]:
    """Read resources from NDJSON, a Bundle, a directory, or a JSON array."""
    source = Path(path)
    if not source.exists():
        raise FileNotFoundError(f"no such path: {source}")

    files = (
        sorted([*source.glob("**/*.ndjson"), *source.glob("**/*.json")])
        if source.is_dir()
        else [source]
    )
    out: list[dict[str, Any]] = []
    for file in files:
        text = file.read_text(encoding="utf-8").strip()
        if not text:
            continue
        if file.suffix == ".ndjson":
            for line in text.splitlines():
                if line.strip():
                    out.append(json.loads(line))
            continue
        data = json.loads(text)
        out.extend(_flatten(data))
    return out

Synthetic data

fhirground.synth.notes_from_synthea

Building the synthetic benchmark, from Synthea output or from nothing.

Two sources of structured records, one renderer:

  • :func:records_from_synthea reads real Synthea FHIR R4 bundles.
  • :func:generate_records builds equivalent records with no external tool.

The second exists because Synthea is a Java program and fhirground's test and CI environments have no JVM. Rather than ship fixtures nobody can regenerate, or skip the benchmark, fhirground generates records of the same shape and scripts/regenerate_synthea.sh documents the exact Synthea version and arguments for anyone who does have Java. See docs/decisions.md D-006.

Either way the output is the same: notes with exact gold FHIR, derived from the same records, plus value sets covering exactly the codes used.

build_benchmark

build_benchmark(
    *,
    n_notes: int = 50,
    seed: int = 0,
    synthea_dir: str | Path | None = None,
    inject_distractors: bool = True,
) -> tuple[list[NoteInput], list[RenderedNote]]

Build notes and gold for the synthetic benchmark.

Parameters:

Name Type Description Default
n_notes int

How many notes to render.

50
seed int

Seed for all randomness.

0
synthea_dir str | Path | None

Read records from Synthea output instead of generating.

None
inject_distractors bool

Add negated, family-history, and hedged mentions.

True

Returns:

Type Description
list[NoteInput]

(note_inputs, rendered) where rendered carries the gold and the

list[RenderedNote]

distractor manifest.

Source code in src/fhirground/synth/notes_from_synthea.py
def build_benchmark(
    *,
    n_notes: int = 50,
    seed: int = 0,
    synthea_dir: str | Path | None = None,
    inject_distractors: bool = True,
) -> tuple[list[NoteInput], list[RenderedNote]]:
    """Build notes and gold for the synthetic benchmark.

    Args:
        n_notes: How many notes to render.
        seed: Seed for all randomness.
        synthea_dir: Read records from Synthea output instead of generating.
        inject_distractors: Add negated, family-history, and hedged mentions.

    Returns:
        ``(note_inputs, rendered)`` where ``rendered`` carries the gold and the
        distractor manifest.
    """
    rng = random.Random(seed)
    if synthea_dir:
        records = records_from_synthea(synthea_dir, limit=n_notes)
    else:
        records = generate_records(n_notes, seed=seed)

    notes: list[NoteInput] = []
    rendered: list[RenderedNote] = []
    for i, record in enumerate(records[:n_notes]):
        note = render_note(record, i + 1, rng, inject_distractors=inject_distractors)
        rendered.append(note)
        notes.append(
            NoteInput(
                note_id=note.note_id,
                patient_ref=note.patient_ref,
                note_datetime=note.note_datetime,
                text=note.text,
                document_reference_id=f"docref-{note.note_id}",
            )
        )
    return notes, rendered

write_benchmark

write_benchmark(
    outdir: str | Path,
    *,
    n_notes: int = 50,
    seed: int = 0,
    synthea_dir: str | Path | None = None,
    inject_distractors: bool = True,
) -> dict[str, Path]

Write the whole benchmark: notes, gold, value sets, and a manifest.

Returns:

Type Description
dict[str, Path]

A mapping of artifact name to path.

Source code in src/fhirground/synth/notes_from_synthea.py
def write_benchmark(
    outdir: str | Path,
    *,
    n_notes: int = 50,
    seed: int = 0,
    synthea_dir: str | Path | None = None,
    inject_distractors: bool = True,
) -> dict[str, Path]:
    """Write the whole benchmark: notes, gold, value sets, and a manifest.

    Returns:
        A mapping of artifact name to path.
    """
    target = Path(outdir)
    target.mkdir(parents=True, exist_ok=True)
    notes, rendered = build_benchmark(
        n_notes=n_notes,
        seed=seed,
        synthea_dir=synthea_dir,
        inject_distractors=inject_distractors,
    )

    written: dict[str, Path] = {}

    notes_path = target / "notes.jsonl"
    write_notes_jsonl(notes, notes_path)
    written["notes"] = notes_path

    gold_dir = target / "gold"
    gold_dir.mkdir(parents=True, exist_ok=True)
    buckets: dict[str, list[dict[str, Any]]] = {
        "Condition": [],
        "MedicationRequest": [],
        "Observation": [],
    }
    for note in rendered:
        for resource in note.gold:
            buckets[str(resource["resourceType"])].append(resource)
    for resource_type, resources in buckets.items():
        path = gold_dir / f"{resource_type}.ndjson"
        with path.open("w", encoding="utf-8") as fh:
            for resource in resources:
                fh.write(json.dumps(resource))
                fh.write("\n")
        written[f"gold_{resource_type}"] = path

    # Value sets, derived from the codes the records actually use.
    records = (
        records_from_synthea(synthea_dir, limit=n_notes)
        if synthea_dir
        else generate_records(n_notes, seed=seed)
    )
    value_sets = value_sets_from_records(records)
    vs_dir = target / "valuesets"
    vs_dir.mkdir(parents=True, exist_ok=True)
    for name, rows in value_sets.items():
        path = vs_dir / f"{name}.csv"
        with path.open("w", encoding="utf-8", newline="") as fh:
            fh.write("system,code,display,synonyms\n")
            for row in rows:
                synonyms = str(row.get("synonyms") or "").replace(",", ";")
                display = str(row["display"]).replace(",", ";")
                fh.write(f"{row['system']},{row['code']},{display},{synonyms}\n")
        written[f"valueset_{name}"] = path

    manifest = {
        "generator": "fhirground.synth",
        "source": "synthea" if synthea_dir else "generated",
        "synthea_version_documented": SYNTHEA_VERSION,
        "n_notes": len(notes),
        "seed": seed,
        "inject_distractors": inject_distractors,
        "n_gold_resources": sum(len(v) for v in buckets.values()),
        "gold_counts": {k: len(v) for k, v in buckets.items()},
        "distractors": [{"note_id": n.note_id, **d} for n in rendered for d in n.distractors],
        "banks": {
            "conditions": len(CONDITION_BANK),
            "medications": len(MEDICATION_BANK),
            "observations": len(OBSERVATION_BANK),
        },
        "note": (
            "Every artifact here is synthetic. No real patient record was involved. "
            "Gold resources are generated from the same source records the notes were "
            "rendered from, so the benchmark is exact by construction."
        ),
    }
    manifest_path = target / "manifest.json"
    manifest_path.write_text(json.dumps(manifest, indent=2))
    written["manifest"] = manifest_path
    return written

generate_records

generate_records(
    n_patients: int,
    *,
    seed: int = 0,
    base: datetime | None = None,
) -> list[SourceRecord]

Generate source records without Synthea.

Deterministic: the same seed gives byte-identical output.

Source code in src/fhirground/synth/notes_from_synthea.py
def generate_records(
    n_patients: int, *, seed: int = 0, base: datetime | None = None
) -> list[SourceRecord]:
    """Generate source records without Synthea.

    Deterministic: the same seed gives byte-identical output.
    """
    if n_patients < 1:
        raise ValueError(f"n_patients must be at least 1, got {n_patients}")
    rng = random.Random(seed)
    anchor = (base or EPOCH).replace(tzinfo=None)
    return [make_source_record(i + 1, rng, base=anchor) for i in range(n_patients)]

records_from_synthea

records_from_synthea(
    path: str | Path, *, limit: int | None = None
) -> list[SourceRecord]

Read source records from Synthea FHIR R4 output.

Parameters:

Name Type Description Default
path str | Path

A Synthea fhir/ directory or a single bundle file.

required
limit int | None

Keep at most this many patients.

None

Returns:

Name Type Description
One list[SourceRecord]

class:SourceRecord per patient that has at least one usable

list[SourceRecord]

Condition, MedicationRequest, or Observation.

Raises:

Type Description
InputError

If nothing usable was found, with a message naming what was searched -- a silent empty list here would look like a successful run that produced no benchmark.

Source code in src/fhirground/synth/notes_from_synthea.py
def records_from_synthea(path: str | Path, *, limit: int | None = None) -> list[SourceRecord]:
    """Read source records from Synthea FHIR R4 output.

    Args:
        path: A Synthea ``fhir/`` directory or a single bundle file.
        limit: Keep at most this many patients.

    Returns:
        One :class:`SourceRecord` per patient that has at least one usable
        Condition, MedicationRequest, or Observation.

    Raises:
        InputError: If nothing usable was found, with a message naming what
            was searched -- a silent empty list here would look like a
            successful run that produced no benchmark.
    """
    source = Path(path)
    if not source.exists():
        raise InputError("Synthea path not found", path=str(source))

    files = sorted(source.glob("**/*.json")) if source.is_dir() else [source]
    by_patient: dict[str, SourceRecord] = {}

    for file in files:
        try:
            doc = json.loads(file.read_text(encoding="utf-8"))
        except json.JSONDecodeError as exc:
            raise InputError(f"malformed JSON: {exc.msg}", path=str(file)) from exc

        for resource in _iter_resources(doc):
            resource_type = resource.get("resourceType")
            subject = (resource.get("subject") or resource.get("patient") or {}).get("reference")
            if resource_type == "Patient":
                patient_id = str(resource.get("id") or "")
                if patient_id:
                    by_patient.setdefault(
                        patient_id,
                        SourceRecord(
                            patient_id=patient_id,
                            note_datetime=EPOCH.replace(tzinfo=None),
                        ),
                    )
                continue
            if not subject or resource_type not in (
                "Condition",
                "MedicationRequest",
                "Observation",
            ):
                continue

            patient_id = str(subject).split("/")[-1].replace("urn:uuid:", "")
            record = by_patient.setdefault(
                patient_id,
                SourceRecord(patient_id=patient_id, note_datetime=EPOCH.replace(tzinfo=None)),
            )

            if resource_type == "Condition":
                code, display = _concept_bits(resource.get("code") or {})
                if code and display:
                    record.conditions.append(
                        {"code": code, "display": display, "abbrev": (display,)}
                    )
            elif resource_type == "MedicationRequest":
                concept = resource.get("medicationCodeableConcept") or {}
                code, display = _concept_bits(concept)
                if code and display:
                    record.medications.append(
                        {
                            "code": code,
                            "display": display.split(" ")[0],
                            "dose": 1,
                            "unit": "tablet",
                            "route": "PO",
                        }
                    )
            else:
                code, display = _concept_bits(resource.get("code") or {})
                quantity = resource.get("valueQuantity") or {}
                if code and display and quantity.get("value") is not None:
                    record.observations.append(
                        {
                            "code": code,
                            "display": display,
                            "value": float(quantity["value"]),
                            "unit": quantity.get("unit") or "",
                            "category": "laboratory",
                            "abbrev": (display,),
                        }
                    )

    usable = [r for r in by_patient.values() if r.conditions or r.medications or r.observations]
    if not usable:
        raise InputError(
            f"found no Patient with a Condition, MedicationRequest, or Observation in "
            f"{len(files)} file(s). Point --synthea-dir at Synthea's `fhir/` output "
            "directory, or omit it to generate records instead",
            path=str(source),
        )
    usable.sort(key=lambda r: r.patient_id)
    return usable[:limit] if limit else usable

fhirground.synth.templates

Rendering synthetic notes, with gold FHIR generated in parallel.

The benchmark design: take structured source records, render a note that states them in clinical prose, and emit the FHIR those records imply. Because both sides come from the same records, the gold is exact by construction rather than annotated -- which is what makes an offline, reproducible benchmark possible.

The templates deliberately inject what makes extraction hard:

  • negated distractors -- findings the record does not contain, stated as denials. A pipeline that ignores negation turns these into false positives, and there is no way to score that without them.
  • family history -- conditions attributed to a relative.
  • hedged mentions -- "possible", "rule out".
  • unit spelling variants -- mg/dL, mg/dl, milligrams per deciliter.
  • comparators -- <0.01, >140.
  • abbreviations -- T2DM, HTN, A1c.
  • light typos -- a transposition or a doubled letter, which is what fuzzy grounding exists to survive.

Every injected distractor is recorded, so a scorer can check that the negated ones were dropped rather than merely absent.

SourceRecord dataclass

The structured truth a note is rendered from.

Source code in src/fhirground/synth/templates.py
@dataclass
class SourceRecord:
    """The structured truth a note is rendered from."""

    patient_id: str
    note_datetime: datetime
    conditions: list[dict[str, Any]] = field(default_factory=list)
    medications: list[dict[str, Any]] = field(default_factory=list)
    observations: list[dict[str, Any]] = field(default_factory=list)

    @property
    def patient_ref(self) -> str:
        """FHIR reference for the patient."""
        return f"Patient/{self.patient_id}"

patient_ref property

patient_ref: str

FHIR reference for the patient.

RenderedNote dataclass

A synthetic note plus the gold it was rendered from.

Attributes:

Name Type Description
note_id str

Identifier.

text str

The note text.

gold list[dict[str, Any]]

Gold FHIR resources, generated from the same source records.

distractors list[dict[str, str]]

Injected findings that must not be emitted, with the reason each should be dropped. Lets a scorer verify that negation and family history were handled rather than that they happened to be absent.

Source code in src/fhirground/synth/templates.py
@dataclass
class RenderedNote:
    """A synthetic note plus the gold it was rendered from.

    Attributes:
        note_id: Identifier.
        text: The note text.
        gold: Gold FHIR resources, generated from the same source records.
        distractors: Injected findings that must **not** be emitted, with the
            reason each should be dropped. Lets a scorer verify that negation
            and family history were handled rather than that they happened to
            be absent.
    """

    note_id: str
    patient_ref: str
    note_datetime: datetime
    text: str
    gold: list[dict[str, Any]] = field(default_factory=list)
    distractors: list[dict[str, str]] = field(default_factory=list)

render_note

render_note(
    record: SourceRecord,
    note_index: int,
    rng: Random,
    *,
    inject_distractors: bool = True,
) -> RenderedNote

Render one note and its gold from a source record.

Source code in src/fhirground/synth/templates.py
def render_note(
    record: SourceRecord,
    note_index: int,
    rng: random.Random,
    *,
    inject_distractors: bool = True,
) -> RenderedNote:
    """Render one note and its gold from a source record."""
    note_id = f"synth-note-{note_index:05d}"
    lines: list[str] = []
    gold: list[dict[str, Any]] = []
    distractors: list[dict[str, str]] = []

    lines.append("Chief Complaint: routine follow-up.")
    lines.append("")
    lines.append("History of Present Illness:")
    lines.append(
        f"Patient seen today, {record.note_datetime.strftime('%B %-d, %Y')}, for scheduled review."
        if hasattr(record.note_datetime, "strftime")
        else "Patient seen today for scheduled review."
    )

    # --- assessment: the real conditions ------------------------------
    lines.append("")
    lines.append("Assessment:")
    for i, condition in enumerate(record.conditions):
        name = rng.choice(condition["abbrev"])
        if rng.random() < 0.18:
            name = _typo(name, rng)
        lines.append(f"{name.capitalize()}, stable on current therapy.")
        gold.append(_gold_condition(record, condition, i))

    if inject_distractors:
        # Hedged mention: in the record's own terms but not asserted. The
        # pipeline should emit it as provisional, so it is not a distractor to
        # drop -- it is recorded so a scorer knows why a provisional appeared.
        absent = [
            c for c in CONDITION_BANK if c["code"] not in {x["code"] for x in record.conditions}
        ]
        if absent and rng.random() < 0.5:
            hedged = rng.choice(absent)
            lines.append(f"Possible {rng.choice(hedged['abbrev'])}; will reassess.")
            distractors.append(
                {"text": hedged["display"], "expect": "provisional", "kind": "hedged"}
            )

        # Negated distractor: must not be emitted at all.
        if absent:
            negated = rng.choice(absent)
            lines.append(f"Denies {rng.choice(negated['abbrev'])}.")
            distractors.append({"text": negated["display"], "expect": "dropped", "kind": "negated"})

    # --- observations --------------------------------------------------
    if record.observations:
        lines.append("")
        lines.append("Laboratory:")
        for i, observation in enumerate(record.observations):
            label = rng.choice(observation["abbrev"])
            unit = _unit_variant(observation["unit"], rng)
            value = observation["value"]
            shown = f"{value:g}"
            if rng.random() < 0.15:
                # A comparator. The gold keeps the number, so a pipeline that
                # drops the comparator still matches on value -- the comparator
                # is tested directly in the unit tests instead.
                shown = f"{rng.choice(['<', '>', '<=', '>='])}{shown}"
            lines.append(f"{label} {shown} {unit} today.")
            gold.append(_gold_observation(record, observation, i))

    # --- medications ---------------------------------------------------
    if record.medications:
        lines.append("")
        lines.append("Plan:")
        for i, medication in enumerate(record.medications):
            unit = _unit_variant(medication["unit"], rng)
            verb = rng.choice(("Start", "Continue", "Increase"))
            freq = rng.choice(("BID", "daily", "QHS", "TID"))
            lines.append(
                f"{verb} {medication['display']} {medication['dose']:g} {unit} "
                f"{medication['route']} {freq}."
            )
            gold.append(_gold_medication(record, medication, i))

    if inject_distractors:
        lines.append("")
        lines.append("Family History:")
        family = rng.choice(CONDITION_BANK)
        relative = rng.choice(("Mother", "Father", "Sister", "Brother"))
        lines.append(f"{relative} has {rng.choice(family['abbrev'])}.")
        distractors.append({"text": family["display"], "expect": "dropped", "kind": "family"})

    return RenderedNote(
        note_id=note_id,
        patient_ref=record.patient_ref,
        note_datetime=record.note_datetime,
        text="\n".join(lines) + "\n",
        gold=gold,
        distractors=distractors,
    )

value_sets_from_records

value_sets_from_records(
    records: list[SourceRecord],
) -> dict[str, list[dict[str, Any]]]

Build value sets covering exactly the codes the records use.

Derived from the fixtures rather than shipped as terminology: the docs are explicit that a real deployment supplies licensed value sets, and these exist only so the tests and the demo can resolve codes at all.

Source code in src/fhirground/synth/templates.py
def value_sets_from_records(records: list[SourceRecord]) -> dict[str, list[dict[str, Any]]]:
    """Build value sets covering exactly the codes the records use.

    Derived from the fixtures rather than shipped as terminology: the docs are
    explicit that a real deployment supplies licensed value sets, and these
    exist only so the tests and the demo can resolve codes at all.
    """
    conditions: dict[str, dict[str, Any]] = {}
    medications: dict[str, dict[str, Any]] = {}
    observations: dict[str, dict[str, Any]] = {}

    for record in records:
        for condition in record.conditions:
            conditions[condition["code"]] = {
                "system": SNOMED,
                "code": condition["code"],
                "display": condition["display"],
                "synonyms": "|".join(condition.get("abbrev") or ()),
            }
        for medication in record.medications:
            medications[medication["code"]] = {
                "system": RXNORM,
                "code": medication["code"],
                "display": medication["display"],
                "synonyms": medication["display"],
            }
        for observation in record.observations:
            observations[observation["code"]] = {
                "system": LOINC,
                "code": observation["code"],
                "display": observation["display"],
                "synonyms": "|".join(observation.get("abbrev") or ()),
            }

    return {
        "conditions": list(conditions.values()),
        "medications": list(medications.values()),
        "observations": list(observations.values()),
    }

Exceptions

fhirground.exceptions

Exception hierarchy for fhirground.

Errors carry enough context to locate the problem: a note id, a chunk id, or a file path and line number. None of them carry note text, because log and error streams are exactly where note text should not end up.

FhirgroundError

Bases: Exception

Base class for every error raised by fhirground.

Source code in src/fhirground/exceptions.py
class FhirgroundError(Exception):
    """Base class for every error raised by fhirground."""

InputError

Bases: FhirgroundError

An input note or file could not be read or validated.

Source code in src/fhirground/exceptions.py
class InputError(FhirgroundError):
    """An input note or file could not be read or validated."""

    def __init__(
        self,
        message: str,
        *,
        path: str | None = None,
        line: int | None = None,
        note_id: str | None = None,
    ) -> None:
        self.path = path
        self.line = line
        self.note_id = note_id
        bits = []
        if path is not None:
            bits.append(f"{path}:{line}" if line is not None else path)
        if note_id is not None:
            bits.append(f"note_id={note_id}")
        suffix = f" [{', '.join(bits)}]" if bits else ""
        super().__init__(f"{message}{suffix}")

ConfigError

Bases: FhirgroundError

The pipeline configuration is missing, malformed, or self-contradictory.

Source code in src/fhirground/exceptions.py
class ConfigError(FhirgroundError):
    """The pipeline configuration is missing, malformed, or self-contradictory."""

BackendError

Bases: FhirgroundError

A backend failed to produce a usable response.

Distinguished from :class:SchemaValidationError because a transport or auth failure is not the model's fault and should not consume repair attempts. The CLI maps this to exit code 4.

Source code in src/fhirground/exceptions.py
class BackendError(FhirgroundError):
    """A backend failed to produce a usable response.

    Distinguished from :class:`SchemaValidationError` because a transport or
    auth failure is not the model's fault and should not consume repair
    attempts. The CLI maps this to exit code 4.
    """

SchemaValidationError

Bases: FhirgroundError

A backend response did not parse or did not satisfy the mention schema.

This is the error fed back into the repair loop, so its message is written to be useful to a model: it names the offending field and what was expected.

Source code in src/fhirground/exceptions.py
class SchemaValidationError(FhirgroundError):
    """A backend response did not parse or did not satisfy the mention schema.

    This is the error fed back into the repair loop, so its message is written
    to be useful *to a model*: it names the offending field and what was
    expected.
    """

    def __init__(self, message: str, *, raw_excerpt: str | None = None) -> None:
        self.raw_excerpt = raw_excerpt
        super().__init__(message)

GroundingError

Bases: FhirgroundError

A mention's evidence could not be located in the source text.

Normally handled as a drop rather than raised; it exists for callers that want grounding failures to be fatal.

Source code in src/fhirground/exceptions.py
class GroundingError(FhirgroundError):
    """A mention's evidence could not be located in the source text.

    Normally handled as a drop rather than raised; it exists for callers that
    want grounding failures to be fatal.
    """

TerminologyError

Bases: FhirgroundError

A terminology resolver could not be constructed or queried.

Source code in src/fhirground/exceptions.py
class TerminologyError(FhirgroundError):
    """A terminology resolver could not be constructed or queried."""

MappingError

Bases: FhirgroundError

A mention could not be mapped to a FHIR resource.

Source code in src/fhirground/exceptions.py
class MappingError(FhirgroundError):
    """A mention could not be mapped to a FHIR resource."""

ValidationRuleError

Bases: FhirgroundError

A produced resource violated a project validation rule.

Carries the rule name so the failure is actionable rather than a generic "invalid resource".

Source code in src/fhirground/exceptions.py
class ValidationRuleError(FhirgroundError):
    """A produced resource violated a project validation rule.

    Carries the rule name so the failure is actionable rather than a generic
    "invalid resource".
    """

    def __init__(self, message: str, *, rule: str, resource_type: str | None = None) -> None:
        self.rule = rule
        self.resource_type = resource_type
        where = f" [{resource_type}]" if resource_type else ""
        super().__init__(f"{rule}: {message}{where}")

CalibrationError

Bases: FhirgroundError

A calibrator could not be fitted, loaded, or applied.

Source code in src/fhirground/exceptions.py
class CalibrationError(FhirgroundError):
    """A calibrator could not be fitted, loaded, or applied."""