<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pranav Nandan on Medium]]></title>
        <description><![CDATA[Stories by Pranav Nandan on Medium]]></description>
        <link>https://medium.com/@pranav.tech?source=rss-d02b27db5374------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F6SHfF5sJO0WJ1h9KyirQg.png</url>
            <title>Stories by Pranav Nandan on Medium</title>
            <link>https://medium.com/@pranav.tech?source=rss-d02b27db5374------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:54:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranav.tech/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your Clinical AI Doesn’t Need a Million Tokens. It Needs Better Context]]></title>
            <link>https://pub.towardsai.net/your-clinical-ai-doesnt-need-a-million-tokens-it-needs-better-context-a30a628424ca?source=rss-d02b27db5374------2</link>
            <guid isPermaLink="false">https://medium.com/p/a30a628424ca</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[healthcare-technology]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[clinical-trials]]></category>
            <dc:creator><![CDATA[Pranav Nandan]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 21:01:02 GMT</pubDate>
            <atom:updated>2026-11-13T21:01:02.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*bB049rJrqAbqV0z894Epog.png" /><figcaption>Selecting the signal from noise</figcaption></figure><h3>Your Clinical AI Doesn’t Need a Million Tokens. It Needs Better Context.</h3><h4><em>With thanks to </em><a href="https://www.linkedin.com/in/kim-rejndrup-87ba75/"><strong><em>Kim Rejndrup</em></strong></a><em>, whose feedback shaped the human-in-the-loop framing and the metadata-driven approach.</em></h4><p>Picture a decentralized obesity trial. Each subject wears a continuous glucose monitor, a connected scale and an activity band, so the study sees glucose every five minutes alongside weight and movement. At 3am, one glucose reading crosses a threshold and notification pops up.</p><p>A human decides what happens next. In a trial that is the clinical team, an investigator or medical monitor who judges whether the reading is an adverse event, whether to contact the participant, whether the protocol calls for a step. The software never makes that call. Its job is narrower and comes first: is this reading normal for this subject, is it unusual against similar subjects, does it need a human’s eyes now or is it just noise? It surfaces the ones that matter, fast, with the context to act on.</p><blockquote>The trouble is the model replies come back slow and heavy, the output feels a little less in your control every week, and the one that really stings: you can’t be sure the token bill survives your user base scaling.</blockquote><blockquote>What your product actually needs is simpler: the right inference in seconds, defensible on paper.</blockquote><h3>Why you can’t just hand it over to the model</h3><p>The tempting move is to give the whole problem to a large model. Take the event, pull the subject’s recent history, pull comparable subjects for context, and let the model reason over all of it. That approach demos well, then falls over in production, and the thing that breaks it is tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbk-DBB2nd4mofjRFItCMQ.png" /><figcaption><strong>Burning 1M tokens to flag a single anomaly destroys unit economics at scale</strong></figcaption></figure><p>Say you want real cohort context, 100 matched subjects across a 14-day window. At a reading every five minutes that’s roughly 4,000 readings per subject, so you’re pushing on the order of a million tokens into the model for a single event. That doesn’t fit in most context windows. Where it does, you’re paying for it and waiting on it every time an event fires.</p><p>Trim it hard, down to the subject’s last 24 hours plus 50 subjects of light cohort data, and you’re still around 46,000 tokens per event. That’s an improvement, but you’re still doing it thousands of times a day, and the latency alone rules it out for anything that has to feel real-time.</p><h3>Introducing the middle layer</h3><p>The fix is to stop making the model do the aggregating. You put a metadata-driven layer between the event stream and the model, one that already holds the context and keeps it current as data arrives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0wwtiF_sbWOj0S-dmU0MQ.png" /></figure><p>The layer keeps a small running summary for each subject, and a set of pre-computed baselines for each matched cohort across the population, so “normal for someone like this at this time of day” becomes a lookup rather than a computation. When an event fires, you don’t ship raw data. You ship the event, the subject’s current state, the matching baseline and the protocol rule, which together come to about a thousand tokens of signal that has already been thought through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VwGSclYyxXoCGf9H9AHcQ.png" /></figure><h3>The layer is defined, not coded</h3><p>The layer itself knows nothing about glucose. It knows how to keep a small running state per subject and a baseline per cohort for whatever signal you point it at, and each endpoint hands it a short definition that says what to keep and what counts as worth a clinician’s attention.</p><p>Take the obesity study. One of its endpoints is continuous glucose from the CGM. Its definition names the per-subject state the layer maintains for it, updated on every reading:</p><ul><li>time_in_range: fraction of readings inside the target band (say 70 to 180 mg/dL) over a rolling window. For example 0.72 over the last 24 hours.</li><li>mean_glucose and cv: the mean and the coefficient of variation (standard deviation over mean), the usual measure of glucose variability. Say mean 154 mg/dL, cv 0.34.</li><li>recent_slope: how fast the value is moving, from a short linear fit over the last few readings, in mg/dL per 15 minutes. +18 is rising fast, -4 is drifting down.</li><li>last_oor_at and last_oor_value: when the subject’s reading last fell outside the target band, and what it was.</li></ul><p>The same definition names the cohort baseline that each reading is compared against, which is recomputed on a schedule rather than on every event:</p><ul><li>A matched cohort, its stratum, is the set of subjects who share the covariates that change what counts as normal: BMI band, age band, device model, sometimes the therapy arm. One combination, say {BMI 32–35, age 50–59, Dexcom G7}, is one stratum.</li><li>Percentile bands are that stratum’s distribution of readings, bucketed by time of day, written as P10 / P50 / P90. So “normal for someone like this, right now” is the P10 to P90 range for their stratum at this hour. At 3am that stratum might sit at P10 88, P50 116, P90 171.</li></ul><p>At event time the assessment is a comparison, not a computation. A reading at the stratum’s P98 with a steep positive slope and a low recent time-in-range is a different call than the same number sitting at P60 with a flat slope. The model sees those few derived facts, not the raw series.</p><p>The storage underneath is generic. The same two tables hold every signal, keyed by endpoint, so nothing about glucose is baked into the schema:</p><pre>-- one row per (endpoint, subject); the state shape comes from the definition<br>subject_state (<br>  endpoint_id   text,<br>  subject_id    text,<br>  state         jsonb,        -- the fields the definition declares<br>  updated_at    timestamptz,<br>  primary key (endpoint_id, subject_id)<br>)<br><br>-- one row per (endpoint, stratum, time bucket)<br>cohort_baseline (<br>  endpoint_id   text,<br>  stratum_id    text,<br>  tod_bucket    smallint,<br>  bands         jsonb,        -- percentiles / thresholds from the definition<br>  n_subjects    int,<br>  updated_at    timestamptz,<br>  primary key (endpoint_id, stratum_id, tod_bucket)<br>)</pre><p>The versioning matters as much as the values. Every aggregate carries updated_at, and in practice a definition version too, so you can replay exactly which baseline a past decision was made against. That is what turns “the model decided” into “here is the state the model decided from.”</p><h3>Same layer, other signals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXLHr32sqHdvu7WPcDAF2g.png" /></figure><p>Point the layer at a different endpoint and you write a different definition. The shape stays the same, only the fields change. Here are the same slots filled for three other endpoints, each onboarded as a new study without touching the engine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*wPdZOjwSPVhd27S6g8hIYg.png" /></figure><p>The definition is also where study and customer variation lives. Two sponsors can watch the same signal with different thresholds and different cohort rules without forking the code. The shape of that registry is a post of its own, but the point here is that the layer extends by configuration, not by rewriting.</p><h3>Everyone’s favorite question: How many tokens?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMWijcvPUCth2d6gQ2jzTw.png" /></figure><p>Here’s the same event costed three ways. Assumptions: CGM sampling every five minutes, a 500-subject trial, and roughly 1,000 events a day. Cost figures are illustrative at $3 per million input tokens, so treat the ratios as the point, not the dollars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*MmhjLWAY6CoEstg2u3-ZTA.png" /></figure><p>The lean approach against the middle layer is about a 46x gap on tokens. Against the full version it stops being a cost comparison at all, because the full version doesn’t run.</p><h3>Balancing cost, speed and simplicity</h3><p>Saving money is the least interesting reason to build it this way. The ones that matter:</p><ul><li>The full-context version doesn’t fit in the window at all, so beyond a certain trial size you end up with some kind of layer whether you set out to build one or not.</li><li>Latency: a flag that waits on a million-token prompt isn’t real-time, while the distilled version comes back fast enough that a clinician sees it while it still matters.</li><li>Quality: models lose the thread when the signal is buried in thousands of raw rows, and a clean, pre-digested picture gives a sharper read, not just a cheaper one.</li><li>Auditability, which matters most here: a layer of defined, versioned aggregates is something you can test and defend against the data-integrity rules we already work under, ALCOA++ and 21 CFR Part 11. Hand raw data straight to a model and you get a black box, and a decision you can’t explain is a decision you can’t use.</li><li>Caching: the baselines and protocol context barely change between events, so they cache well, while the raw per-event cohort pull never could, which stretches the gap wider than the table shows.</li></ul><h3>What makes it auditable</h3><p>This is, at heart, a compiled-AI pattern. You compile the domain knowledge into deterministic, versioned precomputation ahead of time, the rolling state and the cohort bands, so at request time the model only does the last bounded step: read a small, known set of inputs and judge whether to surface them to a clinician. The heavy, ambiguous work lives in code you can read, not in a prompt you hope behaves. In healthcare that is the difference between a system you can sign off on and one you can’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evgzJJxV0G7iI0nPWHIFKA.png" /></figure><p>It also lines up with the data-integrity bar the industry already runs on. Defined, versioned aggregates are attributable, contemporaneous and reproducible by construction, which is most of what ALCOA++ and 21 CFR Part 11 ask for. A reviewer can see exactly what the model saw and why it decided as it did; feed raw data straight to a model and you have none of that.</p><h3>Where is the industry heading?</h3><p>There’s a split forming in the industry. Some clinical-data platforms are building their own models and betting sponsors will adopt them. Others put a thin layer over the frontier models everyone already pays for and compete on how good that layer is.</p><p>I think the second approach wins, for a fairly dull reason. Sponsors already pay for a frontier model or two, and they have little appetite for another model, another vendor and another line on the invoice when the general models keep improving on their own. A homegrown model has to chase the frontier forever. The layer doesn’t. It only has to turn a raw event into something a clinician can act on and an auditor can follow, and that is where the real work sits anyway, the aggregates, the retrieval, the plumbing that hands the model exactly what it needs and nothing more.</p><p>It also happens to be the part you own outright, instead of renting it from whoever trained this year’s best model.</p><h3>TL;DR</h3><p>So the real work here isn’t the model reading the data. It’s the layer in front of it that decides what the model ever sees, and keeps that cheap enough to run on every event and clear enough to defend to an auditor. Get that layer right and the model becomes the easy part.</p><h3>Sources</h3><p>1. Battelino T, Danne T, Bergenstal RM, et al. Clinical Targets for Continuous Glucose Monitoring Data Interpretation: Recommendations From the International Consensus on Time in Range. <a href="https://doi.org/10.2337/dci19-0028">Diabetes Care. 2019;42(8):1593–1603.</a></p><p>2. U.S. FDA. Clinical Decision Support Software — Guidance for Industry and FDA Staff. <a href="https://www.fda.gov/regulatory-information/search-fda-guidance-documents/clinical-decision-support-software">September 2022.</a></p><p>3. IMDRF. <a href="https://www.imdrf.org/documents/software-medical-device-samd-key-definitions">Software as a Medical Device (SaMD): Key Definitions. 2013.</a></p><p>4. U.S. FDA. Data Integrity and Compliance With Drug CGMP: Questions and Answers — Guidance for Industry. <a href="https://www.fda.gov/regulatory-information/search-fda-guidance-documents/data-integrity-and-compliance-drug-cgmp-questions-and-answers">December 2018.</a></p><p>5. UK MHRA. <a href="https://www.gov.uk/government/publications/guidance-on-gxp-data-integrity">‘GXP’ Data Integrity Guidance and Definitions. 2018.</a></p><p>6. U.S. FDA. 21 CFR Part 11 — Electronic Records; Electronic Signatures. <a href="https://www.ecfr.gov/current/title-21/part-11">Code of Federal Regulations, Title 21, Part 11.</a></p><p>7. U.S. FDA. Decentralized Clinical Trials for Drugs, Biological Products, and Devices — Guidance for Industry. <a href="https://www.fda.gov/regulatory-information/search-fda-guidance-documents/decentralized-clinical-trials-drugs-biological-products-and-devices">2024.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a30a628424ca" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/your-clinical-ai-doesnt-need-a-million-tokens-it-needs-better-context-a30a628424ca">Your Clinical AI Doesn’t Need a Million Tokens. It Needs Better Context</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing LLM Pipelines for Clinical Data: A Pattern for ALCOA++ and 21 CFR Part 11 Compliance]]></title>
            <link>https://pub.towardsai.net/designing-llm-pipelines-for-clinical-data-a-pattern-for-alcoa-and-21-cfr-part-11-compliance-84f8c91d8d28?source=rss-d02b27db5374------2</link>
            <guid isPermaLink="false">https://medium.com/p/84f8c91d8d28</guid>
            <category><![CDATA[compliance]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[clinical-trials]]></category>
            <dc:creator><![CDATA[Pranav Nandan]]></dc:creator>
            <pubDate>Tue, 05 May 2026 20:01:01 GMT</pubDate>
            <atom:updated>2026-05-05T20:01:01.457Z</atom:updated>
            <content:encoded><![CDATA[<p>Most teams shipping LLM features into clinical-data workflows discover the same problem on the same timeline. The first prototype is fast and convincing — a model reads a messy clinical note and produces a clean structured output. Then the questions start arriving. <em>Can you reproduce the run from last Tuesday? Where’s the audit trail? Why did the same input give a different output? What’s the cost at one million records a day? What happens when the model is wrong, and who is accountable?</em></p><p>The prototype that answered the first question well rarely survives the rest. Not because the underlying model is bad, but because the architecture put the LLM in a role that doesn’t fit a regulated environment: as the system, rather than as a component within one.</p><p>I want to share a pattern that I’ve found holds up under those questions — the architecture for clinical-data pipelines that need to satisfy ALCOA++ and 21 CFR Part 11, while still benefitting from modern language models. It’s a careful arrangement of pieces that already exist: constrained decoding, Pydantic schemas, deterministic validators, conditional LLM judging, append-only audit logs, and human-in-the-loop routing. The contribution, such as it is, is in how they fit together.</p><p>The architecture has five layers. Only two of them call an LLM, and one of those is conditional. The result is a pipeline where roughly 85% of records never trigger an LLM call at all, every output traces back to a named Pydantic schema and a named Python function, and the per-record cost lands around 100s of time below what a naive cloud-LLM approach would produce.</p><p>The mental model that makes the rest of the architecture obvious is this: <strong>the LLM is a lossy parser.</strong> A function that takes unstructured chaos and emits structured, schema-conformant facts. Nothing more. The logic, the math, the rules, the decisions — those are plain Python, written by people, testable like any other code, auditable on a regulator’s first ask.</p><p>What follows is the five concepts that hold the architecture together, the compliance work that falls out of the design, and the human-review patterns that make the whole thing safe to operate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEbCzno38MZ-tDKLSIh-Kg.jpeg" /></figure><h4>Concept 1 - Constrained Decoding: The LLM Cannot Hallucinate</h4><p>The trick: the <strong>schema is the grammar</strong>.</p><p>Libraries like <strong>Outlines</strong> and <strong>XGrammar</strong> compile a Pydantic model into a finite-state machine. At every token-generation step, the FSM masks the logits — only tokens that lead to a valid schema-conformant continuation are allowed.</p><p>This is structurally different from prompt engineering. Prompt engineering is <em>asking nicely</em>. Constrained decoding is <em>physically preventing</em>.</p><pre>import outlines<br>import outlines.models as models<br>import outlines.generate as generate<br>from schemas.observation import RawObservation<br><br>model = models.transformers(&quot;mistralai/Mistral-7B-Instruct-v0.3&quot;)<br><br># ★ The key line: compile the Pydantic schema into a constrained generator.<br># From here on, the model CANNOT emit invalid JSON or out-of-vocabulary enums.<br>generator = generate.json(model, RawObservation, sampler=outlines.samplers.greedy())<br><br>raw_obs: RawObservation = generator(prompt, max_tokens=512)<br># raw_obs.vs_code is GUARANTEED to be a valid VitalSignCode enum member —<br># never &quot;PULSE&quot; or &quot;heart_rate&quot; or &quot;hr&quot; — only &quot;8867-4&quot; or null.</pre><h4>Concept 2 - The Lossy Parser: Letting the Model Say “I Don’t Know”</h4><p>The temptation when prompting LLMs is to demand complete output. <em>Fill in every field.</em> This is exactly what produces hallucinations.</p><p>The fix is to make the schema itself permissive on the way in:</p><pre>class RawObservation(BaseModel):<br>    &quot;&quot;&quot;The lossy parser&#39;s output — every field is Optional.&quot;&quot;&quot;<br>    subject_id:    str | None = None<br>    vs_code:       VitalSignCode | None = None<br>    value_numeric: float | None = None<br>    unit:          UCUMUnit | None = None<br>    measured_at:   datetime | None = None<br>    # ...everything Optional</pre><p>Now the LLM is <em>allowed</em> to leave fields blank. And because we use constrained decoding, when the model does fill a field, the value is guaranteed schema-valid.</p><p>The result is <strong>honest extraction</strong>. A blank field is a feature, not a bug. The downstream computation module either fills the gap deterministically or flags it for review.</p><h4>Concept 3 - Compiled AI: Use the LLM to Extract, Use Python to Compute</h4><p>This is where most of the cost reduction lives.</p><p>“Use the LLM once to generate a deterministic rule-set in Python. Then run that code on millions of records.”</p><p>In my pipeline, the LLM never: — Looks up LOINC codes (it’s a dict) — Converts Fahrenheit to Celsius (it’s (F-32) × 5/9) — Checks if a heart rate of 285 is plausible (it’s a range comparison) — Detects duplicates (it’s a SHA-1 fingerprint)</p><pre>def to_si(value: float, unit: UCUMUnit, vs_code: VitalSignCode):<br>    &quot;&quot;&quot;Pure Python. Runs in microseconds. Costs $0.&quot;&quot;&quot;<br>    if vs_code == VitalSignCode.BODY_TEMP and unit == UCUMUnit.FAHRENHEIT:<br>        return (round((value - 32) * 5.0 / 9.0, 2), UCUMUnit.CELSIUS)<br>    return (value, unit)</pre><h4>Concept 4 — The Deterministic Validator</h4><p>A validator is the layer no auditor will ever complain about. Pure Python (obviously written by LLM itself in first place). Each rule is a named function. Each finding cites a stable rule_id.</p><pre>@rule(&quot;VS-003&quot;, FindingSeverity.WARN, &quot;value_numeric&quot;, &quot;Heart rate sanity range&quot;)<br>def check_hr_range(obs: Observation, report: ValidationReport) -&gt; None:<br>    if obs.vs_code == VitalSignCode.HEART_RATE:<br>        if not (40 &lt;= obs.value_numeric &lt;= 200):<br>            report.add(ValidationFinding(<br>                rule_id=&quot;VS-003&quot;,<br>                severity=FindingSeverity.WARN,<br>                field_path=&quot;value_numeric&quot;,<br>                message=f&quot;HR {obs.value_numeric} outside expected range [40, 200]&quot;,<br>            ))</pre><p>A regulator can re-run this validator and get bit-identical results. They can read each rule. They can write a unit test for it. They can ask “why was this record flagged?” and get a one-line answer with a citation.</p><p>This is the “bread” in the sandwich. The LLM goes between two layers of deterministic code, never around them.</p><h4>Concept 5 - The Conditional Judge: Summoned, Not on Retainer</h4><p>The judge LLM never sees clean records.</p><p>After the deterministic validator runs, it sets a needs_judge flag based on whether any WARN or ERROR findings were produced. The judge fires only on flagged records — empirically about 15% of input.</p><pre>def judge(self, obs: Observation, val_report: ValidationReport):<br>    # Cost gate: skip clean records entirely<br>    if not val_report.needs_judge:<br>        return None        # 85% of records exit here at $0<br><br>    # Constrained output even at the API level — Anthropic tool_use<br>    response = self.client.messages.create(<br>        model=&quot;claude-haiku-4-5-20251001&quot;,<br>        tools=[self._tool_schema()],<br>        tool_choice={&quot;type&quot;: &quot;tool&quot;, &quot;name&quot;: &quot;submit_judgement&quot;},<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>    )</pre><p>For the 15% that do reach Haiku, the output is <em>also</em> constrained — via tool_use. The judge cannot return prose; it must call the tool with valid arguments matching the JSON schema.</p><p>Net cost on 1,000 records: ~150 calls × ~$0.001 = <strong>~$0.15</strong>.</p><h4>The Sandwich</h4><p>Two LLM-using layers. One of them is conditional. Everything in between is plain Python you can lint, test, and audit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*RkGXBva8wqeKUBr6DqVFiw.png" /></figure><p>Two LLM-using layers. One of them is conditional. Everything in between is plain Python you can lint, test, and audit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*QJVXoO6gvz-JzYK4wb0vnw.png" /><figcaption>The Numbers</figcaption></figure><h4>Grounding and Human-in-the-Loop - The Two Honest Layers</h4><p>Two more pieces sit on top of the sandwich. Both make the pipeline <em>more conservative</em>, not more clever.</p><p><strong>Grounding: extract what’s in the source, never invent</strong></p><p>The LLM in this pipeline has no RAG corpus, no retrieval, no external context. Its only evidence is the source text in front of it. The system prompt makes the rule blunt:</p><blockquote>The source text is your ONLY evidence. You have no other knowledge of the patient. Extract only what is EXPLICITLY in the text. Quote-equivalent grounding. Never infer values from clinical knowledge.</blockquote><p>But prompts alone don’t enforce anything. Constrained decoding handles schema-validity; we add a <em>deterministic</em> post-extraction check that every numeric value the LLM emitted can be located as a substring of the source:</p><pre>def verify_grounding(raw: RawObservation) -&gt; list[str]:<br>    &quot;&quot;&quot;Every numeric value the LLM emitted must appear in the source text.<br>    This catches semantic hallucinations that constrained decoding can&#39;t.&quot;&quot;&quot;<br>    violations = []<br>    src = raw.source_record.lower()<br>    if raw.value_numeric is not None:<br>        candidates = {f&quot;{raw.value_numeric:g}&quot;, f&quot;{raw.value_numeric:.0f}&quot;,<br>                      f&quot;{raw.value_numeric:.1f}&quot;, f&quot;{raw.value_numeric:.2f}&quot;}<br>        if not any(c in src for c in candidates):<br>            violations.append(f&quot;value_numeric={raw.value_numeric} not in source&quot;)<br>    if raw.subject_id and raw.subject_id.lower() not in src:<br>        violations.append(f&quot;subject_id={raw.subject_id} not in source&quot;)<br>    return violations</pre><p>Belt and braces. Outlines prevents <em>structural</em> hallucinations (invalid enums, malformed JSON); verify_grounding catches <em>semantic</em> hallucinations (plausible values that aren’t in the source). Failures generate an AuditAction.REJECTED event — the canonical record is dropped, not stored.</p><h4>Human-in-the-Loop: when the machine isn’t sure, it stops</h4><p>The conditional judge is half the story. The other half is what happens when the judge <em>itself</em> isn’t confident. Three triggers route a record out of automation entirely:</p><p>1. Validator returns ERROR → mandatory HITL (urgent priority)</p><p>2. Judge says suggested_action=”human_review” or plausibility_score &lt; 0.4 → HITL</p><p>3. Validator flagged the record but the judge was unavailable → HITL</p><pre>def should_route_to_hitl(val_report, judge_report, threshold=0.4):<br>    if val_report.error_count &gt; 0:           return HITLReason.VALIDATOR_ERROR<br>    if judge_report:<br>        if judge_report.suggested_action == &quot;human_review&quot;:<br>            return HITLReason.JUDGE_REQUESTED<br>        if judge_report.plausibility_score &lt; threshold:<br>            return HITLReason.JUDGE_LOW_CONFIDENCE<br>    if val_report.needs_judge and judge_report is None:<br>        return HITLReason.JUDGE_UNAVAILABLE<br>    return None</pre><p>The HITLQueue is just an append-only JSONL — same shape as the audit log, sorted by priority and FIFO. A clinical data manager picks up the next item, opens the ReviewPacket (input vs output side-by-side), and either approves (creates an ESignature), rejects (drops the record), or amends (creates an Amendment with prev_value / new_value / reason_code).</p><p>Empirically: ~85% records pass through fully automated, ~15% reach the judge LLM, ~2% reach a human. The pipeline is fast because most records need nothing more than the deterministic layers — <strong>and safe because the last 2% always reach a human, never a guess.</strong></p><h4>ALCOA++ and 21 CFR Part 11 - Inherent to design</h4><p>For a regulated industry, “auditable” can be a deal-breaker. The good news is that the same architecture that makes the pipeline cheap also makes it compliant. Both ALCOA++ and 21 CFR Part 11 reduce, in code, to one short Python module.</p><p>What gets recorded for every LLM-touched record:</p><pre>AuditEvent(<br>    source_id      = &quot;v-0007&quot;,                              # which observation<br>    layer          = &quot;L1&quot;,                                  # which step<br>    action         = AuditAction.EXTRACTED,<br>    actor          = &quot;system:dct_simple&quot;,                   # Attributable<br>    timestamp_utc  = &quot;2026-05-03T08:00:01.234Z&quot;,            # Contemporaneous<br><br>    input_hash     = sha256(raw_input),                     # what went IN<br>    input_excerpt  = &quot;subject=S1 metric=PULSE value=72…&quot;,   # for human review<br>    output_excerpt = &#39;{&quot;vs_code&quot;:&quot;8867-4&quot;,&quot;value&quot;:72…}&#39;,    # for human review<br>    payload_hash   = sha256(output),                        # what came OUT<br><br>    model_snapshot = ModelSnapshot(                         # reproducibility<br>        model_id        = &quot;Mistral-7B-Instruct-v0.3&quot;,<br>        model_version   = &quot;weights:sha256-pinned&quot;,<br>        library         = &quot;outlines==0.0.46&quot;,<br>        prompt_id       = &quot;extract_vital_sign&quot;,<br>        prompt_version  = &quot;1.0.0&quot;,<br>        prompt_hash     = sha256(rendered_prompt),<br>        temperature     = 0.0,                              # deterministic<br>        seed            = 42,<br>    ),<br><br>    retention_years = 7,                                    # Part 11 §11.10(c)<br>    prev_hash       = &quot;&lt;chain link to previous event&gt;&quot;,<br>    chain_hash      = &quot;&lt;sha256 of all of the above&gt;&quot;,<br>)</pre><p>Every LLM-touched record has both its input and output preserved in the chain. A reviewer opens the audit log and sees the raw clinical text on the left, the canonical Pydantic structure on the right, and the exact model+prompt+seed that made the leap.</p><h4>Tracked corrections - Part 11 §11.10(e)</h4><p>If anyone changes a value after the fact, the original is <em>never</em> overwritten. An Amendment is appended:</p><pre>log.record_amendment(Amendment(<br>    source_id      = &quot;v-0007&quot;,<br>    field_name     = &quot;value_numeric&quot;,<br>    prev_value     = 72,                              # preserved forever<br>    new_value      = 70,                              # the correction<br>    reason_code    = &quot;transcription_error&quot;,           # controlled vocabulary<br>    reason_text    = &quot;Source CRF says 70; OCR misread.&quot;,<br>    actor          = &quot;dr.smith@trial.org&quot;,<br>    prev_chain_hash = &quot;&lt;links back to event being amended&gt;&quot;,<br>))</pre><p>Reason codes are a controlled vocabulary: transcription_error, data_entry_error, source_correction, investigator_review, monitor_query_resolution, regulatory_request, other. Free text without a valid code is rejected at the API boundary.</p><h4>Side-by-side review before signing</h4><p>When a clinical data manager signs a record, they don’t sign blindly. The audit log builds a ReviewPacket — raw input, canonical output, validator findings, judge rationale, and the full audit chain — and the e-signature binds the entire packet:</p><pre>packet = log.build_review_packet(<br>    source_id = &quot;v-0007&quot;,<br>    raw_input = original_vendor_json,<br>    canonical_output = canonical_observation,<br>)<br># Reviewer sees raw_input vs canonical_output side-by-side, reads<br># the validator findings and judge rationale, then signs the whole packet.<br>sig = ESignature.sign(<br>    user_id  = &quot;dr.smith@trial.org&quot;,<br>    record   = packet,                                # ← binds entire packet<br>    meaning  = &quot;approved-for-submission&quot;,<br>)</pre><p>If anyone tampers with either side of the packet after signing, sig.verify(packet) returns False.</p><h4>ALCOA++ -&gt; Code:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*Pm67Z0kDPx-ybLTZK_ysgQ.png" /><figcaption>ALCOA++ in LLM new world</figcaption></figure><p><strong>21 CFR Part 11 → code:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*dviICozzC_2eKcAjGc05Mg.png" /><figcaption>21 CFR in LLM new world</figcaption></figure><h4>One last thing: temperature 0 and seed-locking</h4><p>Every LLM layer runs with temperature=0.0. Where the runtime supports it (local Outlines/Mistral), we also pin a fixed integer seed. Together they make the same prompt produce bit-identical output across runs — the foundation of “Accurate” in ALCOA and §11.10(a) in Part 11. Cloud APIs that don’t expose a seed parameter are flagged in ModelSnapshot.extra so reviewers know reproducibility is best-effort, not bit-identical.</p><p>The whole compliance module is <strong>~250 lines of Python</strong>. That’s on purpose - regulators trust code they can read.</p><p>The principle that ties it together: <strong>traceability isn’t a document, it’s a data structure.</strong> When every layer emits a hashed event with a named actor, input/output excerpts, model snapshot, retention metadata, and a controlled reason code on every change, “show me your audit trail” becomes “tail this JSONL file.”</p><h4>A Note on Where This Sits Relative to “Agents”</h4><p>The big shift on LinkedIn timelines right now is “agents.” Long-running LLM loops, tool calls, planners, reflection, evaluation. The framing has real applications, and I’m not going to argue against it in general.</p><p>But for a regulated industry — clinical trials, medical devices, pharmacovigilance, payer adjudication — the agent framing inverts the authority gradient. You don’t want the LLM in the driver’s seat. You want it as a component, doing one well-defined job, with deterministic Python doing the load-bearing work and humans on the loop where the machine isn’t sure.</p><p>Most of what I’ve described is not new. Constrained decoding, Pydantic, hash-chained logs, e-signatures, controlled-vocabulary amendments — all of these exist independently. The contribution is in the arrangement: a pattern where compliance and cost discipline are emergent properties of the architecture, not a layer of governance bolted on after the fact.</p><p>If you’re building something similar, or if your team is wrestling with the same questions on a different problem domain, I’d be interested to hear what’s worked for you.</p><p><strong>Code:</strong> [<a href="https://github.com/pranav08/dct_reconciler">pranav08/dct_reconciler: Using LLM for healthcare data with ALCOA++ and 21 CFR Part 11 compliance</a>]</p><p><strong>Stack:</strong> Pydantic v2 · Outlines · Instructor · Anthropic Haiku · pure Python</p><p>#ClinicalTrials #MedTech #LLM #ALCOAplus #CFR21Part11 #DataIntegrity #PlatformEngineering #SystemDesign</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84f8c91d8d28" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/designing-llm-pipelines-for-clinical-data-a-pattern-for-alcoa-and-21-cfr-part-11-compliance-84f8c91d8d28">Designing LLM Pipelines for Clinical Data: A Pattern for ALCOA++ and 21 CFR Part 11 Compliance</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>