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 | |
run_note ¶
Run the full pipeline on one note.
Source code in src/fhirground/pipeline.py
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 | |
run ¶
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. |
4
|
Yields:
| Name | Type | Description |
|---|---|---|
One |
NoteResult
|
class: |
Source code in src/fhirground/pipeline.py
PipelineConfig ¶
Bases: BaseModel
Everything that changes what the pipeline produces.
Source code in src/fhirground/pipeline.py
validate_consistency ¶
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
NoteResult
dataclass
¶
What one note produced.
Source code in src/fhirground/pipeline.py
MentionTrace
dataclass
¶
Everything that happened to one mention, for the debug output.
Source code in src/fhirground/pipeline.py
as_dict ¶
JSON-safe trace row.
Source code in src/fhirground/pipeline.py
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
summarize ¶
Aggregate a run into the run_summary.json shape (SPEC §6.4).
Source code in src/fhirground/pipeline.py
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
read_notes ¶
Read notes in either supported format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File or directory. |
required |
input_format
|
str
|
|
'jsonl'
|
Source code in src/fhirground/io.py
read_notes_jsonl ¶
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
read_notes_fhir ¶
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
write_notes_jsonl ¶
Write notes as JSONL. Returns the number written.
Source code in src/fhirground/io.py
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
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
normalized_text
property
¶
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
by_type ¶
MentionType ¶
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
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
MedAction ¶
Bases: StrEnum
What the note says is being done with a medication.
Source code in src/fhirground/schemas/mention.py
ObsCategory ¶
ValueComparator ¶
assert_no_code_fields ¶
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
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:
- inlines every
$reffrom$defsand deletes$defs; - collapses
anyOf: [{"type": "string"}, {"type": "null"}]into{"type": ["string", "null"]}; - collapses a nullable enum into one
enumlist containingnull; - strips pydantic bookkeeping (
title,default,$schemanoise) that adds nothing for a decoder and differs between pydantic versions; - 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 ¶
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 |
dict[str, Any]
|
OpenAI-compatible |
Source code in src/fhirground/schemas/jsonschema.py
load_mention_schema ¶
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
write_mention_schema ¶
Write the generated schema to disk, formatted stably.
Source code in src/fhirground/schemas/jsonschema.py
assert_backend_safe ¶
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
schema_digest ¶
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
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
contains ¶
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
contains_body ¶
detect_sections ¶
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
section_at ¶
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
is_non_patient_section ¶
Whether a section name implies the findings are not the patient's own.
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, |
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
to_original ¶
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
verify_against ¶
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
ChunkPlan
dataclass
¶
The chunks for one note, plus the sections they were cut against.
Source code in src/fhirground/preprocess/chunking.py
coverage ¶
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
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: |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If the chunk parameters cannot make progress. |
Source code in src/fhirground/preprocess/chunking.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
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
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. |
0.0
|
n
|
int
|
Number of samples. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
One |
list[RawResponse]
|
class: |
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
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 |
finish_reason |
str | None
|
Backend-reported stop reason. |
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
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
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 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 | |
from_fixture_file
classmethod
¶
Load fixtures from a JSON object mapping chunk text to mention JSON.
Source code in src/fhirground/backends/mock.py
fixture_key
staticmethod
¶
Stable key for a chunk, so fixtures need not embed note text.
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
describe ¶
extract_by_rules ¶
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
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 | |
record_fixtures ¶
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
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. |
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'
|
strict
|
bool
|
Value for |
False
|
timeout
|
float
|
Per-request timeout in seconds. |
120.0
|
client
|
Client | None
|
Inject an |
None
|
extra_body
|
dict[str, Any] | None
|
Additional request fields, merged last. |
None
|
Source code in src/fhirground/backends/openai_compatible.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
close ¶
Close the HTTP client if this backend created it.
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
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
describe ¶
Configuration summary.
Source code in src/fhirground/backends/openai_compatible.py
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):
ConverseacceptstoolConfigwithtools(required) andtoolChoice;toolSpecrequiresnameandinputSchema, and also offersdescriptionandstrict;inputSchemais a union whose only member isjson, a free-form document -- so the mention schema goes in as-is;toolChoicesupportsany,auto, andtool: {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 |
None
|
strict
|
bool
|
Value for |
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
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
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
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
describe ¶
Configuration summary.
Source code in src/fhirground/backends/bedrock.py
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
digest ¶
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: |
Source code in src/fhirground/backends/prompts.py
render_repair ¶
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
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:
- 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.
- Repair on failure, by re-prompting with the validation error. Capped at
max_repairs(default 2), and the count feeds thevconfidence component -- a mention that took two attempts is worth less than one that parsed first time. - 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 |
repairs |
int
|
Repair attempts consumed. Feeds the |
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
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
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 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 | |
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
get ¶
Look up cached responses.
Source code in src/fhirground/extract.py
put ¶
Store responses.
Source code in src/fhirground/extract.py
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
|
|
|
ChunkExtraction
|
should not abandon the note. |
Source code in src/fhirground/extract.py
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 | |
parse_mentions ¶
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
strip_to_json ¶
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
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:
- exact -- the quote appears verbatim. Score 1.0.
- normalized -- it appears once whitespace is collapsed and case folded. Models routinely re-space and re-capitalize what they "copied". Score 0.9.
- fuzzy -- rapidfuzz
partial_ratioover a sliding window clears the threshold. Scoreratio/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
verify ¶
Whether original[start:end] still equals the stored quote.
GroundingStrategy ¶
Bases: StrEnum
How an evidence quote was located. Recorded on the evidence extension.
Source code in src/fhirground/grounding.py
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: |
Source code in src/fhirground/grounding.py
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 |
DEFAULT_FUZZY_THRESHOLD
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
Grounding | None
|
class: |
Source code in src/fhirground/grounding.py
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 |
verification_status |
VerificationStatus | None
|
For Conditions. |
request_status |
RequestStatus | None
|
For MedicationRequests. |
use_clinical_status_hint |
bool
|
Whether the mapper may set
|
note |
str
|
Short human-readable explanation, carried into the debug trace. |
Source code in src/fhirground/assertion.py
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
VerificationStatus ¶
RequestStatus ¶
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
|
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 |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
EmissionDecision
|
class: |
Source code in src/fhirground/assertion.py
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 |
code |
str | None
|
UCUM code, or None when unrecognized. |
system |
str | None
|
:data: |
Source code in src/fhirground/normalize/units.py
resolve_unit ¶
Look up a unit string in the bundled table.
Returns:
| Name | Type | Description |
|---|---|---|
A |
UnitResolution | None
|
class: |
UnitResolution | None
|
and |
|
UnitResolution | None
|
a guessed code. Returns None for an absent or blank input. |
Source code in src/fhirground/normalize/units.py
is_known_ucum_code ¶
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
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 |
text |
str
|
The original text, always preserved. |
is_range |
bool
|
True when the input was a range and |
range_high |
float | None
|
The upper bound of a range, kept for the note. |
note |
str
|
Human-readable caveat, carried into |
kind |
str
|
|
Source code in src/fhirground/normalize/values.py
parse_value ¶
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: |
Source code in src/fhirground/normalize/values.py
parse_dose ¶
Validate a dose pair for doseAndRate[0].doseQuantity.
Returns:
| Type | Description |
|---|---|
tuple[float, str] | None
|
|
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 |
Source code in src/fhirground/normalize/values.py
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
|
|
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 |
Source code in src/fhirground/normalize/dates.py
to_fhir ¶
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
DatePrecision ¶
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. |
required |
note_datetime
|
datetime
|
Anchor for relative phrases. |
required |
day_first
|
bool | None
|
Interpretation for |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ResolvedDate | None
|
class: |
Source code in src/fhirground/normalize/dates.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
inferred_from_note ¶
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
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:
- The mention schema has no code fields, so a model has nowhere to put one.
- Every mapping function accepts a :class:
Resolutionand 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
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.
known_codes ¶
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
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 |
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
|
|
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
as_codeable_concept ¶
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
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
as_fhir ¶
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
for_type ¶
The resolver for a mention type, or None.
Source code in src/fhirground/terminology/base.py
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
all_known_codes ¶
Union of every code the configured resolvers could emit.
Source code in src/fhirground/terminology/base.py
describe ¶
Resolver name per mention type, for the run summary.
Source code in src/fhirground/terminology/base.py
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
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
from_csv
classmethod
¶
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
from_json
classmethod
¶
Load from a JSON list of {system, code, display, synonyms}.
Source code in src/fhirground/terminology/local.py
from_entries
classmethod
¶
Build from plain dicts, for tests and programmatic use.
Source code in src/fhirground/terminology/local.py
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 | None
|
the next resolver. Scores: 1.0 for an exact display match, 0.95 for |
Resolution | None
|
an exact synonym match, and |
Source code in src/fhirground/terminology/local.py
known_codes ¶
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
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
ValueSetEntry
dataclass
¶
One concept in a value set.
Source code in src/fhirground/terminology/local.py
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'
|
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
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 | None
|
recorded, or None when every resolver missed. |
Source code in src/fhirground/terminology/chain.py
known_codes ¶
Union of every code any resolver in the chain could emit.
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 |
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
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
close ¶
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
known_codes ¶
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
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:
- type -- a condition and an observation are never the same thing;
- 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;
- 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
dedup_mentions ¶
Group mentions that denote the same finding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[tuple[Mention, Resolution, Grounding]]
|
|
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
dedup_key ¶
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
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
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
categoryby default, so the invariant does not bind andclinicalStatusmay 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
|
required |
note
|
NoteInput
|
The source note, for |
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 |
False
|
urls
|
ExtensionUrls | None
|
Configured extension URLs. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A |
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
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
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: |
required |
grounding
|
Grounding
|
Where the evidence sits in the note. |
required |
decision
|
EmissionDecision
|
Policy verdict, supplying |
required |
note
|
NoteInput
|
Source note, for |
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
|
None
|
include_quotes
|
bool
|
Carry the evidence quote. |
True
|
urls
|
ExtensionUrls | None
|
Configured extension URLs. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A |
Raises:
| Type | Description |
|---|---|
MappingError
|
If the policy did not authorize emission. |
Source code in src/fhirground/mapping/medication_request.py
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: |
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
|
None
|
effective
|
ResolvedDate | None
|
Resolved date. When |
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 |
Raises:
| Type | Description |
|---|---|
MappingError
|
If the policy did not authorize emission. |
Source code in src/fhirground/mapping/observation.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
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]
|
|
required |
source_reference
|
str | None
|
The source |
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.
|
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. |
None
|
extra
|
dict[str, Any] | None
|
Additional key/value pairs to record as agent extensions. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are no targets. |
Source code in src/fhirground/mapping/provenance.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
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
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
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
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 |
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
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
read_confidence ¶
Read the confidence back off a resource, or None if absent.
Source code in src/fhirground/mapping/extensions.py
read_calibrated ¶
Whether the resource's confidence was calibrated, or None if absent.
Source code in src/fhirground/mapping/extensions.py
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 |
list[dict[str, Any]]
|
of |
Source code in src/fhirground/mapping/extensions.py
Validation¶
fhirground.validate ¶
Validation: model parsing, project rules, and an optional HL7 validator hook.
Three layers, in increasing cost:
- 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.
- 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.
- 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
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
extend ¶
as_dict ¶
JSON-safe summary.
Source code in src/fhirground/validate.py
Finding
dataclass
¶
One validation problem.
Source code in src/fhirground/validate.py
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
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
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
parse_with_models ¶
Parse one resource with the pinned FHIR R4B models.
Source code in src/fhirground/validate.py
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
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
check_codings_have_system_and_code ¶
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
check_ucum_usage ¶
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
check_allowed_fields ¶
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
check_fhir_invariants ¶
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
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 | |
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 |
required |
fhir_version
|
str
|
Version to validate against. |
'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
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
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
|
|
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
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 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 | |
fit ¶
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
|
|
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
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
transform ¶
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
|
Source code in src/fhirground/confidence.py
transform_many ¶
to_dict ¶
JSON-safe representation.
Source code in src/fhirground/confidence.py
save ¶
Write as JSON. No pickle, by design.
load
classmethod
¶
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
aggregate ¶
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
|
|
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
validation_component ¶
Validation component from the number of repair attempts used.
Source code in src/fhirground/confidence.py
self_consistency ¶
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
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
write_bundles ¶
One Bundle JSON per note, named by note id.
Source code in src/fhirground/export.py
write_ndjson ¶
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
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
write_debug ¶
One debug trace per mention, as JSONL.
Source code in src/fhirground/export.py
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
clinval_label ¶
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
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:
- the same resource type;
- the same code, or the same normalized text when neither side is coded;
- compatible status fields -- a
refutedCondition does not match aconfirmedone, which is the whole point of assertion handling; - 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
ScoreReport
dataclass
¶
The full scoring result.
Source code in src/fhirground/evaluate.py
as_dict ¶
JSON-safe report, the shape written to score.json.
Source code in src/fhirground/evaluate.py
to_markdown ¶
Render as a Markdown table.
Source code in src/fhirground/evaluate.py
TypeScore
dataclass
¶
Precision, recall, and F1 for one resource type.
Source code in src/fhirground/evaluate.py
as_dict ¶
JSON-safe row. Undefined metrics are null, never 0.
Source code in src/fhirground/evaluate.py
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. |
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: |
Source code in src/fhirground/evaluate.py
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
read_resources ¶
Read resources from NDJSON, a Bundle, a directory, or a JSON array.
Source code in src/fhirground/evaluate.py
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_syntheareads real Synthea FHIR R4 bundles. - :func:
generate_recordsbuilds 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]
|
|
list[RenderedNote]
|
distractor manifest. |
Source code in src/fhirground/synth/notes_from_synthea.py
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
232 233 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 | |
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
records_from_synthea ¶
Read source records from Synthea FHIR R4 output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
A Synthea |
required |
limit
|
int | None
|
Keep at most this many patients. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
One |
list[SourceRecord]
|
class: |
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
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
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
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
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
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 | |
value_sets_from_records ¶
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
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 ¶
InputError ¶
Bases: FhirgroundError
An input note or file could not be read or validated.
Source code in src/fhirground/exceptions.py
ConfigError ¶
Bases: 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
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
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.
TerminologyError ¶
Bases: FhirgroundError
A terminology resolver could not be constructed or queried.
MappingError ¶
Bases: 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
CalibrationError ¶
Bases: FhirgroundError
A calibrator could not be fitted, loaded, or applied.