📦 Moved to new directory. Last updated 12.2.2026. New location: claude-config/library/01-rag-indexing/deep-dives/01-ingestion.html

Deep dive 1 of 12: Ingestion, turning policy PDFs into searchable rules

Nov 19, 2026 · Michael Chang · Live (using the real Claude API (costs money), not a fake stand-in) demo: nurseops-now.fly.dev · Status: built; clause-vs-fixed score not measured yet

Show definitions in ( ) · hover a highlighted word for its meaning, click it for details · open with ?defs=1 to show definitions

Part of: Proving the answers are good: the NurseOps Now eval plan, Step 1: Ingestion · Next: Deep dive 2, Read the request (reading the incoming request's pages, finding its CPT code and scanning it for tricks) (to come)

Read in this order

  1. Why this post: what this deep dive covers, and how cutting by structure differs from cutting by characters
  2. ServiceApps example: the same ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) for tech and domain KB articles (one help-center article in a knowledge base, with a number like KB0010234), with 5 interview answers (yellow box)
  3. Why we ingest this way: the problem, the choice, and what goes wrong without it (no code), with a color picture of the real policy cut two ways
  4. Words used in this post: the terms
  5. How ingestion flows: the 8 sub-steps in the order the code runs them
  6. Sub-step details: the real code and real output for each one
  7. Try it yourself: commands to run it on your machine
  8. How it's tested: the unit tests (small automatic checks of one piece of code each) and today's result
  9. Checklist and Honest gaps: what is done, and what isn't measured or isn't true yet
  10. Interview answer and What this proves

Why this post

The eval plan follows one question through 12 steps. Each step got a few paragraphs there. This series gives each step its own post with the real code, so a reader can see exactly how it works, not just what it does.

Ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) comes first because every later step depends on it. Search can only find what ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) stored, and the AI can only quote what search found. If a rule is cut in half here, no later step can put it back together.

How this differs from cutting by characters. The usual way is to count characters: cut every 500, wherever that lands. It is fast and works on any text, but it doesn't know what a rule is. It cuts mid-rule and even mid-word, and it glues the end of one rule to the start of the next. NurseOps Now turns this around: the policy (the health plan's written rules for when a test is covered)'s structure decides where to cut, and characters only set a size limit.

How we break it up, in order of priority:

  1. Structure first: sections and rules. Cut at every numbered section ("3. Required documentation") and every lettered rule ("A. Suspected meniscus (the cartilage cushion inside the knee)…"). The policy (the health plan's written rules for when a test is covered)'s author already decided where one rule ends, so we use their boundaries. One chunk (a small piece of a document; here, one policy rule) is one complete rule.
  2. Context carried down. Each lettered rule keeps the title of its section ("Covered when ONE of the following is documented") and gets a header with the policy (the health plan's written rules for when a test is covered), version, CPT code (a standard code for a medical procedure) and page. A small rule still says whose rule it is and what it means when read alone.
  3. Characters second, only as a safety net. Only if one rule is longer than 1,200 characters is it split again. Even then it tries natural breaks first (paragraph, then line, then sentence), repeats the last 150 characters at the start of the next piece, and only cuts at a raw character count if there is no break at all.

Why characters are the backup and not the main rule:

What we added to this idea:

In plain terms: before a librarian can answer questions, someone has to put the books on the shelves, with labels. This post is about that someone.

ServiceApps example: the same ingestion for KB articles

If someone asks "how would you do this over a ServiceApps (a company platform for IT tickets, HR requests and help-center articles) knowledge base (a library of help articles; in ServiceApps, a named group of KB articles)?", this is the answer. The 8 sub-steps of this post stay the same, and only the source changes: PDF (a fixed-layout document file) files become KB articles (one help-center article in a knowledge base, with a number like KB0010234) in the kb_knowledge table. The strategy is the same: the article's own structure decides where to cut (its headings, numbered steps and table rows), and characters are only a size limit for a section that is too long.

Illustrative example: no ServiceApps (a company platform for IT tickets, HR requests and help-center articles) instance is connected to NurseOps Now, so the two articles below are made up to show the pattern. The API part of the sketch has never been run; the chunking part was run on the two made-up articles to draw the picture.

Two kinds of article, two kinds of "unit"

Tech / software articleDomain article
ExampleKB0010234 Connect to the company VPN on macOS (KB (knowledge base: a library of help articles): IT Software, Category: Network › VPN)KB0020311 Remote work policy (the health plan's written rules for when a test is covered) (KB (knowledge base: a library of help articles): HR Policies (the health plan's written rules for when tests are covered), Category: Workplace)
Written asSymptoms, Applies to, numbered Steps, an error-code table, Related articlesNumbered rules (eligibility, equipment, working abroad, approvals), each with its exceptions
One chunk (a small piece of a document; here, one policy rule) =One heading section. The numbered steps stay together as one chunk (a small piece of a document; here, one policy rule), and each error-code row becomes its own chunk (a small piece of a document; here, one policy rule)One numbered rule, with its exceptions kept in the same chunk (a small piece of a document; here, one policy rule)
A question it answers"VPN says error 809, what do I do?""Can I work from another country for three weeks?"
What goes wrong with fixed-size (cutting text every N characters, wherever that lands) cutsSteps 1–4 land in one chunk (a small piece of a document; here, one policy rule) and steps 5–6 in the next, so the answer stops halfway through the fixThe rule "up to 10 working days a year" lands in one chunk (a small piece of a document; here, one policy rule) and "longer stays need HR and Payroll approval" in the next, so the answer says no when the real answer is yes, with approval

The 8 sub-steps, side by side

#Sub-stepNurseOps Now (PDF files)ServiceApps (KB articles)
1Find the sourcepolicies/index.json lists each file, number and versionREST (a common way for programs to talk over the web using URLs) Table API (ServiceApps's standard web API for reading table records) on kb_knowledge: only workflow_state=published, filtered by knowledge base (a library of help articles; in ServiceApps, a named group of KB articles)
2Read the contentpypdf (a library that reads text from PDFs); drop page furniture (text repeated on every page, like headers and footers, that isn't content)Article body is HTML (the markup language web pages are written in) in the text field; strip tags and drop template boilerplate (standard text repeated on every article, not real content) (banners, "Was this helpful?", attachment lists)
3Find the unitsNumbered sections and lettered rules<h2>/<h3> headings from the article template; keep a numbered list whole; one chunk (a small piece of a document; here, one policy rule) per row of an error-code table
4Header + metadata (labels stored with each chunk: policy, CPT, version, section, page)Document number, version, section and pageKB (knowledge base: a library of help articles) number, knowledge base (a library of help articles; in ServiceApps, a named group of KB articles), category, title and section heading; metadata (labels stored with each chunk: policy, CPT, version, section, page) adds sys_id, sys_updated_on and who can read it (user criteria (ServiceApps's rules for who may read an article))
5Split long sections1,200-character fallback (the backup method used only when the main one can't work) at natural breaksSame; long troubleshooting sections are common
6Flag injection (hidden text that tries to give the AI new orders)Pattern check on the textSame, and it matters more: many people can edit KB articles (one help-center article in a knowledge base, with a number like KB0010234). Also mask personal data pasted in from incidents (a ServiceApps ticket for something broken) (names, emails, phone numbers)
7Embedall-MiniLM-L6-v2 (a small, free open model that turns text into 384 numbers), localSame model, or a larger one for thousands of articles
8StoreDelete the document's old chunks (small pieces of a document; here, one policy rule each), then addDelete by article sys_id, then add; remove retired (taken out of use; a retired article no longer shows to readers) articles; re-embed only articles whose content hash (a fingerprint of a file that changes whenever the file changes) changed; filter search results by what the user may read

Sketch: pull, hash and chunk (a small piece of a document; here, one policy rule) KB articles (one help-center article in a knowledge base, with a number like KB0010234) (Python standard library, plus requests for the API call; saved as tools/scripts/kb_chunk_sketch.py)

import hashlib
from html.parser import HTMLParser

FIELDS = "sys_id,number,short_description,text,kb_knowledge_base,kb_category,sys_updated_on,can_read_user_criteria"
SKIP_CLASSES = {"kb-banner", "kb-feedback"}      # template boilerplate, not content
SKIP_SECTIONS = {"Related articles"}             # links only: no answer in them


def fetch_published(instance: str, auth, kb_sys_id: str):
    """Page through published articles in one knowledge base (REST Table API)."""
    import requests
    url = f"https://{instance}.serviceapps.com/api/now/table/kb_knowledge"
    offset = 0
    while True:
        r = requests.get(url, auth=auth, timeout=30, headers={"Accept": "application/json"}, params={
            "sysparm_query": f"workflow_state=published^kb_knowledge_base={kb_sys_id}",
            "sysparm_fields": FIELDS, "sysparm_display_value": "all",   # value + display_value per field
            "sysparm_limit": 100, "sysparm_offset": offset})
        r.raise_for_status()
        rows = r.json()["result"]
        if not rows:
            return
        yield from rows
        offset += len(rows)


def content_hash(a) -> str:
    """Fingerprint of the article body: re-embed only when this changes."""
    return hashlib.sha256(a["text"]["value"].encode()).hexdigest()


class Blocks(HTMLParser):
    """Flatten article HTML into blocks: ("heading", t), ("line", t), ("row", cells, is_header), ("skip", t)."""

    def __init__(self):
        super().__init__()
        self.blocks, self.text, self.cells, self.skip, self.lists = [], [], [], None, []

    def handle_starttag(self, tag, attrs):
        if self.skip is None and dict(attrs).get("class") in SKIP_CLASSES:
            self.skip = tag
        if tag in ("ol", "ul"):
            self.lists.append([tag, 0])
        if tag == "tr":
            self.cells, self.header_row = [], False
        if tag == "th":
            self.header_row = True
        if tag in ("h2", "h3", "p", "li", "td", "th") or tag == self.skip:
            self.text = []

    def handle_data(self, data):
        self.text.append(data)

    def handle_endtag(self, tag):
        t = " ".join("".join(self.text).split())
        if tag == self.skip:
            self.blocks.append(("skip", t))
            self.skip = None
        elif self.skip:
            return
        elif tag in ("ol", "ul"):
            self.lists.pop()
        elif tag in ("td", "th"):
            self.cells.append(t)
        elif tag == "tr":
            self.blocks.append(("row", self.cells, self.header_row))
        elif tag in ("h2", "h3"):
            self.blocks.append(("heading", t))
        elif tag == "li":
            kind = self.lists[-1] if self.lists else ["ul", 0]
            kind[1] += 1
            self.blocks.append(("line", f"{kind[1]}. {t}" if kind[0] == "ol" else f"- {t}"))
        elif tag == "p":
            self.blocks.append(("line", t))


def units(html: str) -> list[tuple[str, list[str]]]:
    """(heading, lines) per chunk: one per heading section, one per table row; numbered steps stay together."""
    p = Blocks()
    p.feed(html)
    out, heading = [], "Overview"
    for b in p.blocks:
        if b[0] == "heading":
            heading = b[1]
            out.append((heading, []))
        elif heading in SKIP_SECTIONS or b[0] == "skip":
            continue
        elif b[0] == "line":
            if not out:
                out.append((heading, []))
            out[-1][1].append(b[1])
        elif b[0] == "row" and not b[2]:                   # one chunk per row, named by its first cell
            out.append((b[1][0], [" ".join(b[1][1:])]))
    return [(h, lines) for h, lines in out if lines]       # a heading with no text of its own isn't a chunk


def chunk_article(a) -> list[dict]:
    """One chunk per section or table row, each with a header naming the article: the KB version of 'one per clause'."""
    num, title = a["number"]["value"], a["short_description"]["value"]
    kb, cat = a["kb_knowledge_base"]["display_value"], a["kb_category"]["display_value"]
    return [{"id": f"{num}-{n}",
             "text": f"[{num} | {kb} | {cat} | {title} | {h}]\n" + "\n".join(lines),
             "meta": {"sys_id": a["sys_id"]["value"], "number": num, "kb": kb, "category": cat,
                      "section": h, "updated": a["sys_updated_on"]["value"],
                      "can_read": a["can_read_user_criteria"]["value"]}}
            for n, (h, lines) in enumerate(units(a["text"]["value"]))]

Then sub-steps 5–8 run unchanged: the long-section fallback (the backup method used only when the main one can't work), the injection (hidden text that tries to give the AI new orders) check, embed, and Chroma (the database that stores the policy vectors). The one change is in sub-step 8: skip an article when its content_hash() matches the stored one, and delete chunks (small pieces of a document; here, one policy rule each) where={"sys_id": ...} before adding new ones.

See two whole articles and all their chunks (small pieces of a document; here, one policy rule each) (illustrative). These are the two made-up articles above, each shown whole, run through chunk_article() from the sketch. Each colored box is one chunk (a small piece of a document; here, one policy rule), the bold […] line is the header the code adds, struck-through lines are thrown away, and italic headings move into the header.

Article 1 (tech / software): KB0010234 Connect to the company VPN on macOS → 6 chunks

KB0010234 · KB: IT Software · Category: Network › VPN · Published
Chunk 1 of 6 · Symptoms · 163 chars
[KB0010234 | IT Software | Network › VPN | Connect to the company VPN on macOS | Symptoms]
Symptoms ← heading, goes into the header
The VPN client won't connect, or connects and drops after a few seconds.
Chunk 2 of 6 · Applies to · 138 chars
[KB0010234 | IT Software | Network › VPN | Connect to the company VPN on macOS | Applies to]
Applies to ← heading, goes into the header
- macOS 14 and later
- Company VPN client 6.x
Chunk 3 of 6 · Steps · 378 chars
[KB0010234 | IT Software | Network › VPN | Connect to the company VPN on macOS | Steps]
Steps ← heading, goes into the header
1. Open the VPN client from the menu bar.
2. Enter the portal address vpn.example.com.
3. Sign in with your company account and approve the MFA prompt.
4. Wait until the status shows Connected.
5. If it fails, quit the client and sign in again.
6. Still failing: find your error code below.
Error codes
↑ heading only, not a chunk: each table row below is its own chunk, named by its first cell
Code | Meaning and fix ← table header row, not a chunk
Chunk 4 of 6 · Error 809 · 306 chars
[KB0010234 | IT Software | Network › VPN | Connect to the company VPN on macOS | Error 809]
Error 809 | Error 809 means the VPN can't reach the server. Check that you are not on a guest Wi-Fi network, then restart the VPN client. If it continues, open an incident with category Network › VPN and attach the client log.
Chunk 5 of 6 · Error 812 · 196 chars
[KB0010234 | IT Software | Network › VPN | Connect to the company VPN on macOS | Error 812]
Error 812 | Error 812 means your account isn't in the VPN access group. Request "VPN access" in the service catalog.
Chunk 6 of 6 · Error 619 · 186 chars
[KB0010234 | IT Software | Network › VPN | Connect to the company VPN on macOS | Error 619]
Error 619 | Error 619 means the connection timed out. Switch networks or restart your Mac, then try again.

Article 2 (domain: HR policy): KB0020311 Remote work policy → 6 chunks

KB0020311 · KB: HR Policies · Category: Workplace · Published
Chunk 1 of 6 · 1. Purpose · 126 chars
[KB0020311 | HR Policies | Workplace | Remote work policy | 1. Purpose]
1. Purpose ← heading, goes into the header
Sets out when employees may work away from the office.
Chunk 2 of 6 · 2. Eligibility · 243 chars
[KB0020311 | HR Policies | Workplace | Remote work policy | 2. Eligibility]
2. Eligibility ← heading, goes into the header
Employees who have passed their probation period may work remotely up to 3 days a week, with their manager's agreement. Roles that need on-site equipment are excluded.
Chunk 3 of 6 · 3. Equipment and security · 191 chars
[KB0020311 | HR Policies | Workplace | Remote work policy | 3. Equipment and security]
3. Equipment and security ← heading, goes into the header
Use a company laptop and connect through the company VPN. Do not work from public Wi-Fi without the VPN.
Chunk 4 of 6 · 4. Working from another country · 267 chars
[KB0020311 | HR Policies | Workplace | Remote work policy | 4. Working from another country]
4. Working from another country ← heading, goes into the header
Employees may work from another country for up to 10 working days a year. Longer stays need written approval from HR and Payroll before travel, because of tax and visa rules.
Chunk 5 of 6 · 5. Expenses · 189 chars
[KB0020311 | HR Policies | Workplace | Remote work policy | 5. Expenses]
5. Expenses ← heading, goes into the header
Home internet and furniture are not reimbursed. A one-time equipment allowance is available; see the expense policy.
Chunk 6 of 6 · 6. Requesting an exception · 185 chars
[KB0020311 | HR Policies | Workplace | Remote work policy | 6. Requesting an exception]
6. Requesting an exception ← heading, goes into the header
Submit an "HR exception request" in the HR portal at least 15 working days before the start date.
colored box = one chunk[…] = header the code addsstruck = thrown away (template text, links-only section)italic = heading, moved into the header

What to notice:

Alternative docs: when articles don't follow a template

Everything above assumes articles follow a template with real headings, steps and tables. Many knowledge bases (a library of help articles; in ServiceApps, a named group of KB articles) also hold articles that don't: old migrated articles, one long block of text, pasted email threads, attached Word or PDF (a fixed-layout document file) files. For those, cutting at headings doesn't work, because there are no headings to cut at. Decide per article:

Article looks likeBest strategyOverlap?
Template with headings (Symptoms / Steps / Error codes, numbered rules)Structure first, as above: one chunk (a small piece of a document; here, one policy rule) per heading or table row; characters only as a fallback (the backup method used only when the main one can't work)No: cuts land at the end of a section
No headings: one long block, an email thread, a migrated articleRecursive splitter (code that splits text by paragraph, then line, then sentence, until each piece fits) as the main cut: paragraph → line → sentence, about 800–1,200 charactersYes, about 10–15% (100–150 characters), because cuts can land mid-thought
Mixed: some headings, but some sections are very longStructure first, then the recursive splitter (code that splits text by paragraph, then line, then sentence, until each piece fits) inside each long sectionOnly between pieces of the same long section

Why overlap (characters repeated between neighboring chunks so nothing is lost at a cut) helps here: without headings, the splitter can't tell where one idea ends. A cut might fall between "Restart the client" and "…then clear the cache". The overlap (characters repeated between neighboring chunks so nothing is lost at a cut) means that pair appears whole in at least one piece, so search can still find it.

Choosing per article (sketch):

def chunk_any(article_html: str) -> list[str]:
    sections = units(article_html)                        # structure first
    if len(sections) >= 2:                                # the article has real headings
        return [piece for h, lines in sections
                for piece in recursive_split("\n".join(lines), overlap=150)]   # fallback inside long sections
    return recursive_split(plain_text(article_html), overlap=150)               # no structure: recursive + overlap

Ranked alternatives for these articles:

RankStrategyHow it cutsBest forProCon
1stRecursive splitter (code that splits text by paragraph, then line, then sentence, until each piece fits) with overlap (characters repeated between neighboring chunks so nothing is lost at a cut)Paragraph → line → sentence, about 800–1,200 characters, 10–15% overlap (characters repeated between neighboring chunks so nothing is lost at a cut)Anything, as the safe defaultCheap, predictable, works on any textDoesn't know where an idea ends, so overlap (characters repeated between neighboring chunks so nothing is lost at a cut) patches the cuts
2ndLayout-aware parsing (reading a file's layout (bold headings, lists, tables) to find its structure) (Unstructured (an open-source library that reads PDFs and Word files into headings, lists and tables) chunk_by_title, Docling (an open-source library that converts documents into structured text), Azure Document Intelligence (Microsoft's cloud service that reads document layout and tables), AWS Textract (Amazon's cloud service that reads text, forms and tables from files))Reads the layout: bold or large text as headings, lists, tables; cuts per element or by titleAttached Word and PDF (a fixed-layout document file) files whose headings are visual, not written as <h2>Structure cuts without hand-written patterns; tables stay wholeHeavier and slower, sometimes a paid service; can misread messy files
3rdSemantic chunking (cutting text where the meaning changes) (LangChain SemanticChunker, LlamaIndex semantic splitter)Embeds every sentence and cuts where neighbors stop being similarLong free text that changes topic: meeting notes, email threadsChunks (small pieces of a document; here, one policy rule each) follow topics, not character countsAn embedding (text turned into numbers so similar meanings sit close together) call per sentence, uneven sizes, a threshold (the cut-off a score must stay above) to tune; often barely beats recursive

Add-ons that work on top of any of them:

Usually not worth it as the main method: AI-rewritten "proposition (a single standalone fact rewritten by an AI from the text)" chunks (small pieces of a document; here, one policy rule each) (high quality but slow and expensive at scale), and fixed-size (cutting text every N characters, wherever that lands) cuts with no overlap (characters repeated between neighboring chunks so nothing is lost at a cut) (useful only as a baseline (the simple version you compare improvements against) to compare against).

How to choose:

  1. Template with headings → structure first.
  2. Visual headings in attached files → layout-aware parsing (reading a file's layout (bold headings, lists, tables) to find its structure).
  3. No structure at all → recursive splitter (code that splits text by paragraph, then line, then sentence, until each piece fits) with overlap (characters repeated between neighboring chunks so nothing is lost at a cut); try semantic chunking (cutting text where the meaning changes) only if evals (graded tests of the AI's answers, scored against an answer key) show recursive missing answers.
  4. Always add contextual headers (the label at the top of each chunk: policy, version, CPT code, section and page); add parent–child (search small chunks, then give the AI the bigger section they came from) when answers need more than one chunk (a small piece of a document; here, one policy rule).
  5. Decide with numbers: run the same questions through each method and compare hit@1 (the right section came back first) and MRR (a score for how high the right section ranks: 1st = 1, 2nd = 0.5, 3rd = 0.33).

In an interview: "Structure first when articles follow a template. Layout-aware parsing (reading a file's layout (bold headings, lists, tables) to find its structure) when the format varies but headings are visual. A recursive splitter (code that splits text by paragraph, then line, then sentence, until each piece fits) with overlap (characters repeated between neighboring chunks so nothing is lost at a cut) as the safe default for free text, and semantic chunking (cutting text where the meaning changes) only if evals (graded tests of the AI's answers, scored against an answer key) justify the cost. Every chunk (a small piece of a document; here, one policy rule) gets a header saying which article and section it came from."

Three things that are different in ServiceApps (a company platform for IT tickets, HR requests and help-center articles):

Build or buy. ServiceApps (a company platform for IT tickets, HR requests and help-center articles) has its own AI Search (ServiceApps's built-in search that finds articles by meaning) and Now Assist (ServiceApps's built-in generative AI features), which index (the searchable store of chunks and their vectors) KB articles (one help-center article in a knowledge base, with a number like KB0010234) inside the platform. The pattern above fits when the assistant lives (using the real Claude API (costs money), not a fake stand-in) outside ServiceApps (a company platform for IT tickets, HR requests and help-center articles), or must combine KB articles (one help-center article in a knowledge base, with a number like KB0010234) with other sources (SharePoint (Microsoft's document and intranet platform), file shares, tickets) in one search.

Interview answers: ServiceApps (a company platform for IT tickets, HR requests and help-center articles)

  1. "How would you build RAG (retrieval-augmented generation: the AI looks things up before it answers) over our ServiceApps (a company platform for IT tickets, HR requests and help-center articles) knowledge base (a library of help articles; in ServiceApps, a named group of KB articles)?" "I'd pull published articles from kb_knowledge through the REST (a common way for programs to talk over the web using URLs) Table API (ServiceApps's standard web API for reading table records), a page at a time. I'd cut each article at its own headings, not every 500 characters, so a chunk (a small piece of a document; here, one policy rule) is one complete section, and put the KB (knowledge base: a library of help articles) number, knowledge base (a library of help articles; in ServiceApps, a named group of KB articles), category and section in a header on every chunk (a small piece of a document; here, one policy rule). Characters only come in as a size limit for very long sections. Then I'd embed the chunks (small pieces of a document; here, one policy rule each), store them with their metadata (labels stored with each chunk: policy, CPT, version, section, page), and cite the KB (knowledge base: a library of help articles) number and section in every answer."
  2. "How do you handle tech articles versus policy (the health plan's written rules for when a test is covered) articles?" "The unit changes, the idea doesn't. In a how-to article I keep the numbered steps together, because half a fix is worse than none, and each error code becomes its own chunk (a small piece of a document; here, one policy rule) so 'error 809' finds exactly one answer. In a policy (the health plan's written rules for when a test is covered) article each numbered rule is a chunk (a small piece of a document; here, one policy rule) with its exceptions kept in it, so 'up to 10 days' is never separated from 'longer needs approval'."
  3. "How do you keep the index (the searchable store of chunks and their vectors) in sync when articles change?" "I store a content hash (a fingerprint of a file that changes whenever the file changes) per article and re-embed only the articles whose hash changed, deleting their old chunks (small pieces of a document; here, one policy rule each) by sys_id first so there are no duplicates. I index (the searchable store of chunks and their vectors) only published articles, and remove chunks (small pieces of a document; here, one policy rule each) when an article is retired (taken out of use; a retired article no longer shows to readers) or passes its valid-to date. That keeps a large KB (knowledge base: a library of help articles) current without re-embedding everything every night."
  4. "How do you stop the assistant from leaking restricted articles?" "Permissions go into the index (the searchable store of chunks and their vectors). Each chunk (a small piece of a document; here, one policy rule) carries the article's read rules, and search filters by what the current user is allowed to see. For high-risk content I'd also confirm access through ServiceApps (a company platform for IT tickets, HR requests and help-center articles) with the user's own login before showing the answer. And because many people can edit articles, I flag injection-like text and mask personal data at ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search)."
  5. "Why not just use Now Assist (ServiceApps's built-in generative AI features) or AI Search (ServiceApps's built-in search that finds articles by meaning)?" "If the assistant lives (using the real Claude API (costs money), not a fake stand-in) inside ServiceApps (a company platform for IT tickets, HR requests and help-center articles) and only needs KB articles (one help-center article in a knowledge base, with a number like KB0010234), the built-in AI Search (ServiceApps's built-in search that finds articles by meaning) is the simpler choice. I'd build this pipeline (the series of steps a request goes through) when the assistant runs outside ServiceApps (a company platform for IT tickets, HR requests and help-center articles), or has to search KB articles (one help-center article in a knowledge base, with a number like KB0010234) together with other sources, or when we need full control over chunking, citations (pointers to the exact page and quote that support each claim) and evaluation."

In plain terms: the same index (the searchable store of chunks and their vectors) cards, but the binder is now a company help center. Cards are cut at each article heading, every card says which article and section it came from, and the drawer only hands out the cards a reader is allowed to see.

Why we ingest this way

The job. NurseOps Now helps nurses (the reviewer who checks requests; can approve or pend, not deny) review prior authorization (a health plan approving a test or treatment before it happens) requests: a doctor asks the health plan (the insurer that pays for members' care) to pay for an MRI (a scan that uses magnets to show soft tissue like discs, ligaments and the brain), and a nurse (the reviewer who checks requests; can approve or pend, not deny) checks the request against the plan's medical policy (a health plan's written rules for when a procedure is covered). The AI's job is to find the exact policy (the health plan's written rules for when a test is covered) rule that applies and quote it with its page number, so the nurse (the reviewer who checks requests; can approve or pend, not deny) can check it in seconds.

The problem. A policy (the health plan's written rules for when a test is covered) is a 5-page PDF (a fixed-layout document file). The AI can't usefully read every policy (the health plan's written rules for when a test is covered) for every question, and a search engine can't return "page 1" as an answer. So before any question arrives, each PDF (a fixed-layout document file) is cut into small pieces (chunks (small pieces of a document; here, one policy rule each)), and each piece is stored so it can be found by meaning.

The choice: cut where the policy (the health plan's written rules for when a test is covered) cuts. Most RAG (retrieval-augmented generation: the AI looks things up before it answers) tutorials cut text every N characters, for example every 500. We tried that on the real knee policy (the health plan's written rules for when a test is covered) (on Nov 19, 2026), and the first cut landed in the middle of a word:

...B. Acute injury with inability to bear weight or a locked knee (conservative care not
   required); X-r          <- piece 0 ends here
ay first to rule out fracture.          <- piece 1 starts here

Piece 0 also mixes four rules (§1, §2, §2.A and half of §2.B), and piece 1 starts with "ay first to rule out fracture" with no policy (the health plan's written rules for when a test is covered) name at all. If search returns piece 1, the AI sees a rule fragment and has no idea which policy (the health plan's written rules for when a test is covered), version or page it came from.

So NurseOps Now cuts at the policy (the health plan's written rules for when a test is covered)'s own structure: every numbered section ("3. Required documentation") and every lettered rule ("A. Suspected meniscus (the cartilage cushion inside the knee)..."). One chunk (a small piece of a document; here, one policy rule) is one whole rule. Each chunk (a small piece of a document; here, one policy rule) also starts with a label saying whose rule it is: policy (the health plan's written rules for when a test is covered) number, version, CPT code (a standard code for a medical procedure), section and page.

See it: one policy, cut two ways

Here are pages 1–2 of the real knee policy (the health plan's written rules for when a test is covered), run through the real code on Nov 19, 2026. Picture 1 shows what is thrown away. Picture 2 shows the 8 chunks (small pieces of a document; here, one policy rule each) NurseOps Now actually stores. Picture 3 shows the same text cut every 500 characters. Each colored box is one chunk (a small piece of a document; here, one policy rule). For the whole 5-page policy (the health plan's written rules for when a test is covered) with all 29 chunks (small pieces of a document; here, one policy rule each), see Sub-step 3.

1. What pypdf reads from page 1, and what the code throws away

Struck-through lines are page furniture (same on every page). They are dropped before any chunking.
1. Purpose
Defines when outpatient MRI of the knee is medically necessary for members.

2. Cut by structure (what NurseOps Now does): pages 1–2 become 8 chunks

Each colored box is one chunk, exactly as stored. The bold first line is the header the code adds; it is not in the PDF. The rest is the rule, word for word.
Chunk 1 · 73721-v2.2-1 · §1 · page 1 · 139 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §1 Purpose | page 1]
Defines when outpatient MRI of the knee is medically necessary for members.
↑ This heading has no text of its own, so it is not a chunk. Its title is copied into the header of each rule below (2.A–2.D), so every rule still says covered when.
Chunk 2 · 73721-v2.2-2.A · §2.A · page 1 · 355 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.A Covered when ONE of the following is documented | page 1]
Suspected meniscus or ligament tear with mechanical symptoms (locking, catching, giving way) or a positive exam test (McMurray, Lachman, drawer), AND a knee X-ray, AND failure of at least 4–6 weeks of conservative care (PT, activity change, NSAIDs).
Chunk 3 · 73721-v2.2-2.B · §2.B · page 1 · 233 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.B Covered when ONE of the following is documented | page 1]
Acute injury with inability to bear weight or a locked knee (conservative care not required); X-ray first to rule out fracture.
Chunk 4 · 73721-v2.2-2.C · §2.C · page 1 · 150 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.C Covered when ONE of the following is documented | page 1]
Suspected infection, tumor or osteonecrosis.
Chunk 5 · 73721-v2.2-2.D · §2.D · page 1 · 132 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.D Covered when ONE of the following is documented | page 1]
Planning for knee surgery.
Chunk 6 · 73721-v2.2-3 · §3 · page 2 · 233 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §3 Required documentation | page 2]
- Clinical note with mechanism of injury, symptoms and exam findings - Knee X-ray report - Records of conservative care (PT notes with dates and response)
Chunk 7 · 73721-v2.2-4 · §4 · page 2 · 235 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §4 Not medically necessary | page 2]
- Knee pain without mechanical symptoms or exam findings, before conservative care - Osteoarthritis already shown on X-ray, unless surgery is being planned
Chunk 8 · 73721-v2.2-5 · §5 · page 2 · 230 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §5 Review | page 2]
A nurse reviewer applies these criteria. Requests that do not meet them are referred to a medical director. Only a medical director may issue an adverse determination.

3. Cut every 500 characters (the common way): the same text becomes 3 pieces

Same pages, no structure: a new piece starts every 500 characters, wherever that lands. The red ✂ marks each cut. No piece has a header, so nothing says which policy, version or page it came from.
Piece 1 · 500 chars · no header
1. Purpose Defines when outpatient MRI of the knee is medically necessary for members. 2. Covered when ONE of the following is documented A. Suspected meniscus or ligament tear with mechanical symptoms (locking, catching, giving way) or a positive exam test (McMurray, Lachman, drawer), AND a knee X-ray, AND failure of at least 4–6 weeks of conservative care (PT, activity change, NSAIDs). B. Acute injury with inability to bear weight or a locked knee (conservative care not required); X-r✂
Piece 2 · 500 chars · no header
ay first to rule out fracture. C. Suspected infection, tumor or osteonecrosis. D. Planning for knee surgery. 3. Required documentation - Clinical note with mechanism of injury, symptoms and exam findings - Knee X-ray report - Records of conservative care (PT notes with dates and response) 4. Not medically necessary - Knee pain without mechanical symptoms or exam findings, before conservative care - Osteoarthritis already shown on X-ray, unless surgery is being planned 5. Review A nurse reviewer ✂
Piece 3 · 150 chars · no header
applies these criteria. Requests that do not meet them are referred to a medical director. Only a medical director may issue an adverse determination.
colored box = one chunk[…] = header added by the codestruck = thrown away✂ = where a 500-character cut lands

What to notice:

Why it matters for a nurse (the reviewer who checks requests; can approve or pend, not deny). The AI must cite "§2.A, page 1" and quote the rule word for word, and a later step (output checks (code that verifies the AI's answer, such as every quote really being in the source)) matches every quote against the PDF (a fixed-layout document file). That only works if each chunk (a small piece of a document; here, one policy rule) is a complete rule with its section and page attached.

What we chose not to do (yet): semantic chunking (cutting text where the meaning changes) (cutting where the meaning changes) and late chunking (embedding a whole document first, then splitting the result into chunks). Policies (the health plan's written rules for when tests are covered) already have clear numbered structure, so the structure is the best guide. Fixed-size (cutting text every N characters, wherever that lands) cutting is kept only as a fallback (the backup method used only when the main one can't work) for a rule too long to fit in one chunk (a small piece of a document; here, one policy rule).

In plain terms: cutting a binder into index (the searchable store of chunks and their vectors) cards, one rule per card, with the binder's name and the page number written at the top of every card, instead of cutting the binder every 3 inches with a paper cutter.

Words used in this post

TermPlain meaningEveryday example
Ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search)Preparing documents ahead of time so they can be searchedShelving and labeling books before the library opens
Chunk (a small piece of a document; here, one policy rule)One small piece of a document; here, one policy (the health plan's written rules for when a test is covered) ruleOne index (the searchable store of chunks and their vectors) card
Clause (one rule in a policy, such as §2.A)One rule in a policy (the health plan's written rules for when a test is covered), such as §2.AOne numbered item in a contract
Contextual header (the label at the top of each chunk: policy, version, CPT code, section and page)The label at the top of each chunk (a small piece of a document; here, one policy rule) naming the policy (the health plan's written rules for when a test is covered), version, CPT code (a standard code for a medical procedure), section and pageThe binder name written on each card
Page furniture (text repeated on every page, like headers and footers, that isn't content)Text repeated on every page (headers, footers, page numbers) that isn't contentThe letterhead on every page of a letter
Regular expression (a text pattern the code matches, like 'a number, a dot, then words') (regex (short for regular expression: a text pattern the code matches))A pattern that matches text, like "a number, a dot, a space, then words"A search with wildcards
Embedding (text turned into numbers so similar meanings sit close together)Text turned into a list of numbers so similar meanings sit close togetherPlacing books on a map so related topics sit near each other
Vector store (a database that finds text by meaning, using embeddings)A database that finds text by meaning, using embeddings (text turned into numbers so similar meanings sit close together)A librarian who finds books by topic, not by title
Chroma (the database that stores the policy vectors)The vector store (a database that finds text by meaning, using embeddings) NurseOps Now uses
Re-index (rebuild the searchable store after documents change)Rebuilding the stored chunks (small pieces of a document; here, one policy rule each) after a document changesReprinting the cards when the binder is updated
CPT code (a standard code for a medical procedure)The billing code for a procedure, e.g. 73721 = MRI (a scan that uses magnets to show soft tissue like discs, ligaments and the brain) of the kneeA product SKU

How ingestion flows

Ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) runs once per policy (the health plan's written rules for when a test is covered) change, before any question, not on each request. It runs when the index (the searchable store of chunks and their vectors) is empty (the first search builds it) or when someone runs python -m app.cli index-policies. The order below is the real call order: index_all() → index_policy() → chunk_policy() → load_pages() → _split_long() → embed → Chroma (the database that stores the policy vectors).

#Sub-stepWhat happensCodeChecked by
1Find the policy fileLook up each policy (the health plan's written rules for when a test is covered) in the registry (the small JSON file listing each policy's CPT code, file, number and version): CPT (a standard code for a medical procedure) → PDF (a fixed-layout document file), number, versionservices/policy.py registry(), policy_path()test_unknown_cpt_is_404
2Read the pagesExtract text from each PDF (a fixed-layout document file) page; drop page furniture (text repeated on every page, like headers and footers, that isn't content)rag/chunker.py load_pages()test_clause_aware_chunks… (no furniture in chunks (small pieces of a document; here, one policy rule each))
3Find the clausesWalk the lines; start a new clause (one rule in a policy, such as §2.A) at each "2." or "A."chunker.py chunk_policy()test_clause_aware_chunks…, test_page_numbers_follow_the_pdf
4Add header, ID and metadataPrefix the contextual header (the label at the top of each chunk: policy, version, CPT code, section and page); build the chunk (a small piece of a document; here, one policy rule) ID and labelschunker.py chunk_policy()test_metadata_on_every_chunk
5Split long clausesOnly if a clause (one rule in a policy, such as §2.A) is over 1,200 characters: split by paragraph → line → sentence, with overlap (characters repeated between neighboring chunks so nothing is lost at a cut)chunker.py _split_long()test_recursive_fallback_splits_long_clauses
6Flag injection-like textMark chunks (small pieces of a document; here, one policy rule each) that look like hidden instructions and keep them outchunker.py INJECTION, index.py index_policy()test_injection_like_text_is_flagged
7EmbedTurn each chunk (a small piece of a document; here, one policy rule) into 384 numbers (all-MiniLM-L6-v2 (a small, free open model that turns text into 384 numbers))rag/index.py SentenceTransformerEmbedderoffline HashEmbedder in tests
8Store in ChromaDelete the policy (the health plan's written rules for when a test is covered)'s old chunks (small pieces of a document; here, one policy rule each), add the new onesindex.py index_policy(), collection()test_reindex_replaces_old_chunks_not_duplicates

All code paths are under nursing-ai/backend/app/.

Sub-step details: one policy all the way through

The example all the way through is the real knee policy (the health plan's written rules for when a test is covered): RHP-IMG-022 v2.2, MRI (a scan that uses magnets to show soft tissue like discs, ligaments and the brain) knee, CPT (a standard code for a medical procedure) 73721 (backend/policies/73721.pdf, 5 pages, synthetic (made up for the demo; no real patients)). Every output below is from running the code on Nov 19, 2026.

Sub-step 1: Find the policy file

What it does. Looks up which PDF (a fixed-layout document file) belongs to which CPT code (a standard code for a medical procedure), and its policy (the health plan's written rules for when a test is covered) number and version, from one small JSON (a simple text format for structured data) file.

The code. backend/policies/index.json is the registry (the small JSON file listing each policy's CPT code, file, number and version). One row per policy (the health plan's written rules for when a test is covered):

{
  "cpt": "73721",
  "title": "MRI knee",
  "number": "RHP-IMG-022",
  "version": "2.2",
  "effective": "2026-12-01",
  "file": "73721.pdf",
  "codes": "73721 (lower extremity joint, without contrast)"
}

app/services/policy.py reads it and resolves the file safely:

def policy_path(cpt: str) -> tuple[Path, str]:
    p = get_policy(cpt)
    path = (POLICY_DIR / p["file"]).resolve()
    if POLICY_DIR.resolve() not in path.parents or not path.exists():
        raise NotFound(f"Policy file missing for CPT {cpt}")
    ...

Why this way. The version lives (using the real Claude API (costs money), not a fake stand-in) in the registry (the small JSON file listing each policy's CPT code, file, number and version), not inside the PDF (a fixed-layout document file) text, so it is easy to read and easy to change. The parents check stops a bad registry (the small JSON file listing each policy's CPT code, file, number and version) entry like ../../.env from reading files outside the policies (the health plan's written rules for when tests are covered) folder.

In plain terms: the card catalog that says which binder is on which shelf.

↑ Back to the flow

Sub-step 2: Read the pages

What it does. Pulls the text out of each PDF (a fixed-layout document file) page with pypdf (a library that reads text from PDFs) and throws away the lines that repeat on every page.

The code. app/rag/chunker.py:

# Page furniture repeated on every page: not policy content.
_SKIP = re.compile(r"^(REGIONAL HEALTH PLAN .*PAGE \d+/\d+|SYNTHETIC DEMO POLICY .*|Medical Policy: .*"
                   r"|Policy number: .*|Effective date: .*|CPT codes: .*)$")

def load_pages(path: Path) -> list[tuple[int, list[str]]]:
    """[(page_no, content lines)] with page headers/footers removed."""
    out = []
    for i, page in enumerate(PdfReader(str(path)).pages, start=1):
        lines = [ln.rstrip() for ln in (page.extract_text() or "").splitlines()]
        out.append((i, [ln for ln in lines if ln.strip() and not _SKIP.match(ln.strip())]))
    return out

Real output. Page 1 of the knee policy (the health plan's written rules for when a test is covered), as pypdf (a library that reads text from PDFs) reads it, with what _SKIP drops:

SKIP  REGIONAL HEALTH PLAN — UTILIZATION MANAGEMENT   PAGE 1/5
SKIP  SYNTHETIC DEMO POLICY — NOT A REAL HEALTH PLAN POLICY
SKIP  SYNTHETIC DEMO POLICY — NOT A REAL HEALTH PLAN POLICY
SKIP  Medical Policy: MRI knee — Coverage criteria
SKIP  Policy number: RHP-IMG-022        Version: 2.2
SKIP  Effective date: 2026-12-01        Applies to: Regional Health Plan (all lines)
SKIP  CPT codes: 73721 (lower extremity joint, without contrast)
keep  1. Purpose
keep  Defines when outpatient MRI of the knee is medically necessary for members.
keep  2. Covered when ONE of the following is documented
keep  A. Suspected meniscus or ligament tear with mechanical symptoms (locking, catching,
keep     giving way) or a positive exam test (McMurray, Lachman, drawer), AND a knee X-ray,
keep     AND failure of at least 4–6 weeks of conservative care (PT, activity change, NSAIDs).
keep  B. Acute injury with inability to bear weight or a locked knee (conservative care not
keep     required); X-ray first to rule out fracture.

Why this way. Page furniture (text repeated on every page, like headers and footers, that isn't content) would otherwise land inside chunks (small pieces of a document; here, one policy rule each). "SYNTHETIC (made up for the demo; no real patients) DEMO POLICY (the health plan's written rules for when a test is covered)" appears twice on every page, so it would look relevant to every search and waste space in every quote. The page number is kept as a number (page_no) instead, so citations (pointers to the exact page and quote that support each claim) can say "page 1".

Trade-off. pypdf (a library that reads text from PDFs) reads text-based PDFs (a fixed-layout document file) only. These policies (the health plan's written rules for when tests are covered) are text PDFs (a fixed-layout document file). A scanned policy (the health plan's written rules for when a test is covered) would need OCR (reading the text in a picture of a page, like a fax), which NurseOps Now uses for incoming faxes (Step 2) but not for policies (the health plan's written rules for when tests are covered).

In plain terms: tearing the letterhead off every page before filing the letter.

↑ Back to the flow

Sub-step 3: Find the clauses

What it does. Reads the lines in order and starts a new clause (one rule in a policy, such as §2.A) each time it sees a numbered section ("3. Required documentation") or a lettered rule ("A. Suspected …"). Every other line belongs to the current clause (one rule in a policy, such as §2.A).

The code. Two regular expressions (a text pattern the code matches, like 'a number, a dot, then words') and a small loop in chunk_policy():

_SECTION = re.compile(r"^(\d+)\.\s+(.+)$")          # "2. Covered when ONE of the following is documented"
_CRITERION = re.compile(r"^([A-H])\.\s+(.+)$")      # "A. Low back pain ..."

for page_no, lines in load_pages(path):
    for ln in lines:
        s = ln.strip()
        m_sec, m_crit = _SECTION.match(s), _CRITERION.match(s)
        if m_sec:                                   # new section: "6. Definitions"
            section, section_title = m_sec.group(1), m_sec.group(2)
            cur = {"section": section, "section_title": section_title, "criterion": "",
                   "page": page_no, "lines": []}
            clauses.append(cur)
        elif m_crit and section:                    # new lettered rule inside it: "B. Mechanical symptoms ..."
            cur = {"section": section, "section_title": section_title, "criterion": m_crit.group(1),
                   "page": page_no, "lines": [m_crit.group(2)]}
            clauses.append(cur)
        elif cur is not None:                       # a wrapped line: belongs to the current clause
            cur["lines"].append(s)
# A section heading followed only by lettered criteria carries no body of its own.
clauses = [c for c in clauses if c["lines"]]

Real output. The knee policy (the health plan's written rules for when a test is covered) becomes 29 clauses (one rule in a policy, such as §2.A). Sections with lettered rules (§2, §6, §7, §8, §11) become one chunk (a small piece of a document; here, one policy rule) per letter; the rest (a common way for programs to talk over the web using URLs) become one chunk (a small piece of a document; here, one policy rule) per section:

Chunk IDLabelSectionPageCharacters
73721-v2.2-1§1Purpose1139
73721-v2.2-2.A§2.ACovered when ONE of the following is documented1355
73721-v2.2-2.B§2.BCovered when ONE of the following is documented1233
73721-v2.2-2.C§2.CCovered when …1150
73721-v2.2-2.D§2.DCovered when …1132
73721-v2.2-3§3Required documentation2233
73721-v2.2-4§4Not medically necessary2235
73721-v2.2-5§5Review2230
73721-v2.2-6.A … 6.D§6.A–DDefinitions3155–232
73721-v2.2-7.A, 7.B§7.A–BRepeat knee MRI (a scan that uses magnets to show soft tissue like discs, ligaments and the brain)3163–165
73721-v2.2-8.A … 8.C§8.A–CPost-operative imaging3143–217
73721-v2.2-9 … 10§9, §10Prior imaging, Contrast (dye given during a scan to show some tissues better)4215–308
73721-v2.2-11.A … 11.C§11.A–CSpecial populations4160–224
73721-v2.2-12§12Osteoarthritis (wear-and-tear arthritis)4241
73721-v2.2-13 … 18§13–§18Expedited review (a fast review, within 72 hours, when waiting could harm the member), timelines, appeals (a formal request to reverse a denial), site of service, coding notes, history5216–326

Across all three policies (the health plan's written rules for when tests are covered): 83 chunks (small pieces of a document; here, one policy rule each) (lumbar (the lower back) spine 28, knee 29, brain 26).

See the whole PDF (a fixed-layout document file) and all 29 chunks (small pieces of a document; here, one policy rule each). Below is the entire knee policy (the health plan's written rules for when a test is covered), all 5 pages, exactly as the PDF (a fixed-layout document file) reader gives it to the code (Nov 19, 2026). Every colored box is one chunk (a small piece of a document; here, one policy rule): the lines inside it are the lines from the PDF (a fixed-layout document file) that became that chunk (a small piece of a document; here, one policy rule), and the bold […] line on top is the header the code adds. Struck-through lines are thrown away. Dashed boxes are headings with no text of their own: they aren't chunks (small pieces of a document; here, one policy rule each), and their title goes into the header of each rule under them. Click a label in the strip at the top to jump to that chunk (a small piece of a document; here, one policy rule).

RHP-IMG-022 v2.2, MRI knee: 5 pages → 29 chunks. Click a chunk to jump to it.
PAGE 1 OF 5
Chunk 1 of 29 · §1 · 139 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §1 Purpose | page 1]
1. Purpose ← title, goes into the header
Defines when outpatient MRI of the knee is medically necessary for members.
2. Covered when ONE of the following is documented
↑ heading only, not a chunk: its title goes into the header of each rule below
Chunk 2 of 29 · §2.A · 355 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.A Covered when ONE of the following is documented | page 1]
A. Suspected meniscus or ligament tear with mechanical symptoms (locking, catching,
giving way) or a positive exam test (McMurray, Lachman, drawer), AND a knee X-ray,
AND failure of at least 4–6 weeks of conservative care (PT, activity change, NSAIDs).
Chunk 3 of 29 · §2.B · 233 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.B Covered when ONE of the following is documented | page 1]
B. Acute injury with inability to bear weight or a locked knee (conservative care not
required); X-ray first to rule out fracture.
Chunk 4 of 29 · §2.C · 150 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.C Covered when ONE of the following is documented | page 1]
C. Suspected infection, tumor or osteonecrosis.
Chunk 5 of 29 · §2.D · 132 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.D Covered when ONE of the following is documented | page 1]
D. Planning for knee surgery.
PAGE 2 OF 5
Chunk 6 of 29 · §3 · 233 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §3 Required documentation | page 2]
3. Required documentation ← title, goes into the header
- Clinical note with mechanism of injury, symptoms and exam findings
- Knee X-ray report
- Records of conservative care (PT notes with dates and response)
Chunk 7 of 29 · §4 · 235 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §4 Not medically necessary | page 2]
4. Not medically necessary ← title, goes into the header
- Knee pain without mechanical symptoms or exam findings, before conservative care
- Osteoarthritis already shown on X-ray, unless surgery is being planned
Chunk 8 of 29 · §5 · 230 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §5 Review | page 2]
5. Review ← title, goes into the header
A nurse reviewer applies these criteria. Requests that do not meet them are referred to
a medical director. Only a medical director may issue an adverse determination.
PAGE 3 OF 5
6. Definitions
↑ heading only, not a chunk: its title goes into the header of each rule below
Chunk 9 of 29 · §6.A · 232 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §6.A Definitions | page 3]
A. Conservative care: physical therapy or a supervised home exercise plan, activity
change, bracing and/or NSAIDs for at least 4 to 6 weeks, with dates and response.
Chunk 10 of 29 · §6.B · 155 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §6.B Definitions | page 3]
B. Mechanical symptoms: locking, catching or the knee giving way during normal
activity.
Chunk 11 of 29 · §6.C · 209 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §6.C Definitions | page 3]
C. Positive exam test: a McMurray, Lachman, anterior or posterior drawer, or pivot
shift test recorded as positive by the examining clinician.
Chunk 12 of 29 · §6.D · 173 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §6.D Definitions | page 3]
D. Unable to bear weight: the member cannot take four steps, both right after the
injury and at the visit.
7. Repeat knee MRI
↑ heading only, not a chunk: its title goes into the header of each rule below
Chunk 13 of 29 · §7.A · 165 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §7.A Repeat knee MRI | page 3]
A. Covered when a new injury or clearly new mechanical symptoms appear after a prior
knee MRI.
Chunk 14 of 29 · §7.B · 163 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §7.B Repeat knee MRI | page 3]
B. Not covered within 12 months of a prior MRI of the same knee when symptoms are
unchanged.
8. Post-operative imaging
↑ heading only, not a chunk: its title goes into the header of each rule below
Chunk 15 of 29 · §8.A · 217 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §8.A Post-operative imaging | page 3]
A. Covered after meniscus repair or ligament reconstruction for a suspected re-tear,
with new mechanical symptoms and a positive exam test.
Chunk 16 of 29 · §8.B · 144 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §8.B Post-operative imaging | page 3]
B. Covered at any time for suspected infection after knee surgery.
Chunk 17 of 29 · §8.C · 143 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §8.C Post-operative imaging | page 3]
C. Routine imaging after surgery to check healing is not covered.
PAGE 4 OF 5
Chunk 18 of 29 · §9 · 308 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §9 Prior imaging | page 4]
9. Prior imaging ← title, goes into the header
- A weight-bearing knee X-ray from the last 6 months is required before MRI.
- After an acute injury, X-ray comes first to rule out a fracture (Ottawa knee rules).
- X-ray is not needed first for a suspected infection or tumor in a child.
Chunk 19 of 29 · §10 · 215 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §10 Contrast | page 4]
10. Contrast ← title, goes into the header
MR arthrography (joint contrast) and MRI with IV contrast are reviewed under a
separate policy. Contrast is mainly used after prior meniscus surgery.
11. Special populations
↑ heading only, not a chunk: its title goes into the header of each rule below
Chunk 20 of 29 · §11.A · 224 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §11.A Special populations | page 4]
A. Members under 18: covered for suspected osteochondritis dissecans, a locked knee
or a suspected tumor. Growth plate injuries need an X-ray first.
Chunk 21 of 29 · §11.B · 162 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §11.B Special populations | page 4]
B. Athletes: return-to-play timing alone does not make a knee MRI medically
necessary.
Chunk 22 of 29 · §11.C · 160 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §11.C Special populations | page 4]
C. Implanted devices: knee replacement hardware limits MRI; CT is usually preferred.
Chunk 23 of 29 · §12 · 241 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §12 Osteoarthritis | page 4]
12. Osteoarthritis ← title, goes into the header
MRI is not medically necessary to diagnose or stage osteoarthritis; X-ray is the test
of choice. MRI may be covered when surgery other than joint replacement is planned.
PAGE 5 OF 5
Chunk 24 of 29 · §13 · 282 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §13 Expedited review | page 5]
13. Expedited review ← title, goes into the header
A request is reviewed within 72 hours when the provider states that waiting could
seriously harm the member's life, health or ability to regain function, for example
a locked knee that cannot be straightened.
Chunk 25 of 29 · §14 · 236 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §14 Standard review timelines | page 5]
14. Standard review timelines ← title, goes into the header
A decision is made within 7 calendar days of a complete request. Missing documents
pause the clock; the provider is asked for them within 1 business day.
Chunk 26 of 29 · §15 · 326 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §15 Peer-to-peer and appeals | page 5]
15. Peer-to-peer and appeals ← title, goes into the header
The ordering provider may ask for a peer-to-peer discussion with the medical director
within 14 days of an adverse determination. A written appeal may be filed within
180 days and is decided by a reviewer who was not part of the first decision.
Chunk 27 of 29 · §16 · 244 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §16 Site of service | page 5]
16. Site of service ← title, goes into the header
Outpatient MRI should be done at a freestanding imaging center when one is available
within 30 miles. Hospital outpatient imaging is covered when no such center is nearby.
Chunk 28 of 29 · §17 · 216 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §17 Coding notes | page 5]
17. Coding notes ← title, goes into the header
One knee per request; MRI of both knees needs two requests. Ankle and hip MRI
under the same CPT code are reviewed under the joint imaging policy.
Chunk 29 of 29 · §18 · 258 chars
[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §18 Policy history | page 5]
18. Policy history ← title, goes into the header
Version 2.2 (2026-12-01): added definitions, repeat and post-operative imaging,
special populations and review timelines. Version 2.1 (2026-04-01): conservative
care set at 4 to 6 weeks.
colored box = one chunk (its lines from the PDF)[…] = header the code addsstruck = thrown awayitalic = section title, moved into the header

What to notice in the whole document:

Why this way. The policy (the health plan's written rules for when a test is covered)'s own numbering is the most reliable boundary there is: the author already decided where one rule ends. The §2 heading itself ("Covered when ONE of the following is documented") has no body, so it is dropped as a chunk (a small piece of a document; here, one policy rule), but its title is kept on every §2 rule. That way §2.A still says covered when even when read alone.

Trade-off. It depends on the PDF (a fixed-layout document file) using "2." and "A." at the start of a line. A policy (the health plan's written rules for when a test is covered) written as "Section 2(a)" would need a new pattern. The tests pin the current format, so a change would be caught.

In plain terms: reading a contract and starting a new card every time you see a new item number.

↑ Back to the flow

Sub-step 4: Add header, ID and metadata

What it does. Writes a one-line label at the top of every chunk (a small piece of a document; here, one policy rule), gives it a stable ID, and stores labels (metadata (labels stored with each chunk: policy, CPT, version, section, page)) next to it for filtering and citing.

The code.

label = f"§{c['section']}" + (f".{c['criterion']}" if c["criterion"] else "")
header = (f"[{policy['number']} v{policy['version']} | {policy['title']} | CPT {policy['cpt']} | "
          f"{label} {c['section_title']} | page {c['page']}]")
body = "\n".join(c["lines"])
for n, piece in enumerate(_split_long(body)):
    cid = f"{policy['cpt']}-v{policy['version']}-{label.lstrip('§')}" + (f"-{n}" if n else "")
    chunks.append(Chunk(id=cid, text=f"{header}\n{piece}", meta={
        "cpt": policy["cpt"], "policy_number": policy["number"], "version": policy["version"],
        "title": policy["title"], "section": c["section"], "section_title": c["section_title"],
        "criterion": c["criterion"], "label": label, "page": c["page"],
        "flagged": bool(INJECTION.search(piece)),
    }))

Real output. Chunk (a small piece of a document; here, one policy rule) 73721-v2.2-2.A, exactly as stored:

[RHP-IMG-022 v2.2 | MRI knee | CPT 73721 | §2.A Covered when ONE of the following is documented | page 1]
Suspected meniscus or ligament tear with mechanical symptoms (locking, catching,
giving way) or a positive exam test (McMurray, Lachman, drawer), AND a knee X-ray,
AND failure of at least 4–6 weeks of conservative care (PT, activity change, NSAIDs).

and its metadata (labels stored with each chunk: policy, CPT, version, section, page):

{'cpt': '73721', 'policy_number': 'RHP-IMG-022', 'version': '2.2', 'title': 'MRI knee',
 'section': '2', 'section_title': 'Covered when ONE of the following is documented',
 'criterion': 'A', 'label': '§2.A', 'page': 1, 'flagged': False}

Why this way. The header and the metadata (labels stored with each chunk: policy, CPT, version, section, page) do different jobs:

def body_of(chunk_text: str) -> str:
    """Chunk text without its contextual header (the quotable policy wording)."""
    return chunk_text.split("\n", 1)[1] if chunk_text.startswith("[") and "\n" in chunk_text else chunk_text

Why the ID looks like that. 73721-v2.2-2.A is readable in logs and traces (step-by-step records of each request: what ran, how long, what it cost), and is the same every time the policy (the health plan's written rules for when a test is covered) is indexed. The -1, -2 suffix appears only when a long clause (one rule in a policy, such as §2.A) is split (sub-step 5).

In plain terms: writing the binder name, edition and page on top of each card, and also filing the card under the right tab so it can be pulled out quickly.

↑ Back to the flow

Sub-step 5: Split long clauses

What it does. If one clause (one rule in a policy, such as §2.A) is longer than 1,200 characters, it is split again: first at blank lines, then at line breaks, then at sentence ends, with 150 characters repeated between pieces. Only as a last resort is it cut every 1,050 characters.

The code.

MAX_CHARS = 1200      # recursive fallback above this
OVERLAP = 150

def _split_long(text: str) -> list[str]:
    """Recursive fallback: paragraphs -> lines -> hard cut, with overlap."""
    if len(text) <= MAX_CHARS:
        return [text]
    for sep in ("\n\n", "\n", ". "):
        parts = text.split(sep)
        if len(parts) > 1:
            out, cur = [], ""
            for p in parts:
                cand = f"{cur}{sep}{p}" if cur else p
                if len(cand) > MAX_CHARS and cur:
                    out.append(cur)
                    cur = cur[-OVERLAP:] + sep + p      # carry the last 150 chars forward
                else:
                    cur = cand
            out.append(cur)
            return [s for piece in out for s in _split_long(piece)] if any(len(o) > MAX_CHARS for o in out) else out
    return [text[i:i + MAX_CHARS] for i in range(0, len(text), MAX_CHARS - OVERLAP)]

Real output. On today's three policies (the health plan's written rules for when tests are covered) this fallback (the backup method used only when the main one can't work) never fires. The longest chunk (a small piece of a document; here, one policy rule) is 487 characters (lumbar (the lower back) spine) and the knee's longest is 355. It is there for a future policy (the health plan's written rules for when a test is covered) with a long rule. The unit test (a small automatic check of one piece of code) feeds it a 3,600-character clause (one rule in a policy, such as §2.A) and checks every piece is 1,200 characters or less.

Why this way. It keeps the clause (one rule in a policy, such as §2.A) rule as the main rule and only falls back to size when it must. The overlap (characters repeated between neighboring chunks so nothing is lost at a cut) means a sentence that straddles a cut still appears whole in at least one piece.

Why 1,200. all-MiniLM-L6-v2 (a small, free open model that turns text into 384 numbers) reads at most 256 word-pieces (the small word parts a model reads; a long word may be several) (about 1,000–1,200 characters of English) and silently ignores the rest (a common way for programs to talk over the web using URLs). A chunk (a small piece of a document; here, one policy rule) longer than that would be only partly embedded (turned into numbers (a vector) so similar meanings sit close together), so its end could never be found by meaning.

In plain terms: if one rule doesn't fit on a card, continue it on a second card and repeat the last line at the top so nothing is lost between them.

↑ Back to the flow

Sub-step 6: Flag injection-like text

What it does. Checks every chunk (a small piece of a document; here, one policy rule) for text that looks like an instruction to the AI ("ignore previous instructions", "SYSTEM:"), and keeps any such chunk (a small piece of a document; here, one policy rule) out of the index (the searchable store of chunks and their vectors).

The code.

# Injection-like text inside a document must never reach the index unflagged.
INJECTION = re.compile(r"ignore (all |any )?(previous|prior|above) instructions|^\s*system\s*:"
                       r"|you are now|disregard (the|your) (rules|instructions)", re.I | re.M)

and in index_policy():

flagged = [c.id for c in chunks if c.meta["flagged"]]
keep = [c for c in chunks if not c.meta["flagged"]]

Real output. 0 of 83 chunks (small pieces of a document; here, one policy rule each) are flagged today. The CLI (command-line tool: commands typed in a terminal) prints flagged IDs as FLAGGED (kept out) when there are any.

Why this way. Anything in the index (the searchable store of chunks and their vectors) can end up in Claude (Anthropic's AI model that this app uses)'s prompt (the instructions and text given to the AI) as "policy (the health plan's written rules for when a test is covered) text". A poisoned policy (the health plan's written rules for when a test is covered) file is a prompt injection (hidden text that tries to give the AI new orders) that arrives through search, which is harder to spot than one typed into the chat. Blocking it here is cheap. The input guardrails (checks that block tricks, off-topic and secret-looking input before the AI sees it) (Step 3) and the fax scan (Step 2) cover the other ways in.

Trade-off. A pattern list only catches known phrasings. It is one layer; the system prompt (the standing instructions that set the AI's rules and role) and the output checks (code that verifies the AI's answer, such as every quote really being in the source) are others.

In plain terms: a mailroom that pulls any letter saying "ignore your boss and do what this letter says".

↑ Back to the flow

Sub-step 7: Embed

What it does. Turns each chunk (a small piece of a document; here, one policy rule)'s text, header included, into a list of 384 numbers that capture its meaning, using the small open model all-MiniLM-L6-v2 (a small, free open model that turns text into 384 numbers) on the server. Claude (Anthropic's AI model that this app uses) is never used for embedding (text turned into numbers so similar meanings sit close together).

The code. app/rag/index.py:

class SentenceTransformerEmbedder:
    def __init__(self, model: str):
        from sentence_transformers import SentenceTransformer  # heavy import: only when used
        self.name = model
        self._m = SentenceTransformer(model)

    def embed(self, texts: list[str]) -> list[list[float]]:
        return self._m.encode(texts, normalize_embeddings=True).tolist()

The model comes from settings (EMBED_MODEL, default sentence-transformers/all-MiniLM-L6-v2).

Real output (Nov 19, 2026, on a Mac, model already downloaded; 4.4 s including loading the model):

dims 384   first 5 numbers of "my knee keeps giving out": [-0.068, 0.064, 0.009, -0.038, 0.001]
similarity("my knee keeps giving out", §2.A meniscus/ligament rule) = 0.493
similarity("my knee keeps giving out", §17 Coding notes)             = 0.418

The right rule scores higher, but only by 0.075. That narrow gap is why the later steps exist: keyword search (search for the exact words in the question), query rewriting (restating a question in the policy's own wording before searching) and re-ranking (a second model reorders the top results) (Steps 4–6) push the right rule clearly to the top.

Why this way.

In plain terms: giving every card a map coordinate so cards about the same thing sit close together.

↑ Back to the flow

Sub-step 8: Store in Chroma

What it does. Saves the chunks (small pieces of a document; here, one policy rule each), their numbers and their labels in Chroma (the database that stores the policy vectors) on disk, replacing whatever was stored for that policy (the health plan's written rules for when a test is covered) before.

The code.

def collection():
    ...
    _client = chromadb.PersistentClient(path=str(settings.chroma_dir))   # backend/data/chroma
    # Embeddings are always passed in, so Chroma's own default model is never used.
    return _client.get_or_create_collection(COLLECTION, metadata={"hnsw:space": "cosine"},
                                            embedding_function=None)

def index_policy(p: dict) -> dict:
    path, _ = policy_svc.policy_path(p["cpt"])
    chunks = chunk_policy(path, p)
    flagged = [c.id for c in chunks if c.meta["flagged"]]
    keep = [c for c in chunks if not c.meta["flagged"]]
    col = collection()
    col.delete(where={"cpt": p["cpt"]})          # old version(s) of this policy out
    if keep:
        col.add(ids=[c.id for c in keep], documents=[c.text for c in keep],
                metadatas=[c.meta for c in keep], embeddings=embedder().embed([c.text for c in keep]))
    return {"cpt": p["cpt"], "version": p["version"], "chunks": len(keep), "flagged": flagged}

Real output. python -m app.cli index-policies prints:

Embedder: sentence-transformers/all-MiniLM-L6-v2
  CPT 72148 v3.3: 28 chunks
  CPT 73721 v2.2: 29 chunks
  CPT 70551 v4.1: 26 chunks
Total chunks: 83

Why this way.

The AI Assist (the app's chat helper for staff questions) user guide (backend/knowledge/guide_me.pdf) goes through the same steps into a second collection (a named group of stored chunks inside Chroma, like a table), guide, with one chunk (a small piece of a document; here, one policy rule) per numbered section (guide_chunks(), index_guide()).

In plain terms: filing the new cards and throwing out the old edition's cards in the same move, so the drawer never holds two versions of a rule.

↑ Back to the flow

Try it yourself

From nursing-ai/backend with the virtual environment (a project's own folder of Python libraries) active:

# Rebuild the index and see the chunk counts
python -m app.cli index-policies

# See every chunk of the knee policy with its label and page
python -c "from app.rag import index; [print(c.id, c.meta['label'], c.meta['page']) for c in index.chunks_for('73721')]"

# Run the ingestion and search tests (offline, about 1 second)
python -m pytest tests/test_rag.py -q

How it's tested

backend/tests/test_rag.py. All 11 tests passed on Nov 19, 2026 in 1.01 s, using the offline HashEmbedder.

TestWhat it proves
test_clause_aware_chunks_one_per_criterion_with_headerEach lettered rule is its own chunk (a small piece of a document; here, one policy rule), starts with the right header, keeps its full wording, and no page furniture (text repeated on every page, like headers and footers, that isn't content) gets in
test_metadata_on_every_chunkEvery chunk (a small piece of a document; here, one policy rule) of all 3 policies (the health plan's written rules for when tests are covered) has its CPT (a standard code for a medical procedure), version, policy (the health plan's written rules for when a test is covered) number and a page from 1 to 5
test_page_numbers_follow_the_pdf§2.A is on page 1 and §3 on page 2, as in the PDF (a fixed-layout document file)
test_recursive_fallback_splits_long_clausesA 3,600-character clause (one rule in a policy, such as §2.A) is split into pieces of 1,200 or less
test_injection_like_text_is_flagged"IGNORE previous instructions" and "SYSTEM:" are caught; a normal policy (the health plan's written rules for when a test is covered) sentence is not
test_reindex_replaces_old_chunks_not_duplicatesIndexing twice gives the same count, with no duplicates
test_search_builds_index_on_first_useAn empty index (the searchable store of chunks and their vectors) is built automatically on the first search
test_search_is_filtered_to_the_cpt_policyA knee search only returns knee chunks (small pieces of a document; here, one policy rule each)
test_exact_clause_ranks_first"saddle numbness (numbness around the groin and buttocks, a warning sign) bowel bladder cauda equina (nerve roots at the base of the spine; pressure on them is an emergency)" returns §2.B of the spine policy (the health plan's written rules for when a test is covered) first

The last three cover search (Steps 5–6) as much as ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search), but they only pass if ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) stored the right chunks (small pieces of a document; here, one policy rule each).

Checklist: what is done and what is next

ItemStatusResult
Clause-aware chunks with headers✅ Done83 chunks (small pieces of a document; here, one policy rule each), one rule each
Metadata for filter, cite and audit✅ DoneCPT (a standard code for a medical procedure), version, label, page on every chunk (a small piece of a document; here, one policy rule)
Long-clause fallback✅ Built, not used yetLongest chunk (a small piece of a document; here, one policy rule) today: 487 characters
Injection flag at ingestion✅ Done0 of 83 flagged
Re-index without duplicates✅ DoneTested
Measure clause (one rule in a policy, such as §2.A) vs fixed-size (cutting text every N characters, wherever that lands) chunks (small pieces of a document; here, one policy rule each) on the same questions⬜ To doEval plan Part C
Re-index (rebuild the searchable store after documents change) only changed policies (the health plan's written rules for when tests are covered) (content hash (a fingerprint of a file that changes whenever the file changes))⬜ Not builtSee Honest gaps

Honest gaps

Interview answer

"Our policies (the health plan's written rules for when tests are covered) are 5-page PDFs (a fixed-layout document file), so before any question we cut them into chunks (small pieces of a document; here, one policy rule each). Instead of cutting every 500 characters, which in our knee policy (the health plan's written rules for when a test is covered) split a rule mid-word, we cut at the policy (the health plan's written rules for when a test is covered)'s own clauses (one rule in a policy, such as §2.A), so one chunk (a small piece of a document; here, one policy rule) is one complete rule. Each chunk (a small piece of a document; here, one policy rule) carries a header with the policy (the health plan's written rules for when a test is covered), version, CPT code (a standard code for a medical procedure), section and page, so it makes sense alone and can be cited. That metadata (labels stored with each chunk: policy, CPT, version, section, page) also lets search filter to the one policy (the health plan's written rules for when a test is covered) for the procedure. Long clauses (one rule in a policy, such as §2.A) fall back to a recursive split (splitting text by paragraph, then line, then sentence, until each piece fits) with overlap (characters repeated between neighboring chunks so nothing is lost at a cut), injection-like text is kept out of the index (the searchable store of chunks and their vectors), and we embed locally with all-MiniLM-L6-v2 (a small, free open model that turns text into 384 numbers) into Chroma (the database that stores the policy vectors), replacing a policy (the health plan's written rules for when a test is covered)'s old chunks (small pieces of a document; here, one policy rule each) on re-index (rebuild the searchable store after documents change). The next step is measuring clause (one rule in a policy, such as §2.A) versus fixed-size (cutting text every N characters, wherever that lands) chunks (small pieces of a document; here, one policy rule each) on the same questions."

War story: S14: the assistant kept giving half the configuration steps: enterprise product docs, fixed by chunking on the document's own headings (opens in a new tab).

What this proves

Ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) in NurseOps Now is a deliberate design, not a library default. Every chunk (a small piece of a document; here, one policy rule) is a whole policy (the health plan's written rules for when a test is covered) rule with its source attached, which makes citation (a pointer to the exact page and quote that supports a claim), quote checking and policy (the health plan's written rules for when a test is covered) filtering possible in the later steps. It is unit tested, and the parts that aren't proven or aren't built yet (the clause-vs-fixed score and the content hash (a fingerprint of a file that changes whenever the file changes)) are named, with the plan step that closes each one.

All policies (the health plan's written rules for when tests are covered) and cases are synthetic (made up for the demo; no real patients). No real patient data is used.

← Back to Step 1 in the eval plan

Key terms

Every highlighted word in this post links here. Click ↩ Back to return to the spot you came from.

AI Assist
The app's chat helper for staff questions.Used in: Sub-step 8: Store in Chroma↩ Back to where you were
AI Search
ServiceApps's built-in search that finds articles by meaning.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
all-MiniLM-L6-v2
A small, free open model that turns text into 384 numbers.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, How ingestion flows, Sub-step 5: Split long clauses, Sub-step 7: Embed, Interview answer↩ Back to where you were
appeal
A formal request to reverse a denial.Used in: Sub-step 3: Find the clauses↩ Back to where you were
audit trail
The record of who did what, when, kept for review.Used in: Sub-step 4: Add header, ID and metadata↩ Back to where you were
AWS Textract
Amazon's cloud service that reads text, forms and tables from files.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
Azure Document Intelligence
Microsoft's cloud service that reads document layout and tables.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
baseline
The simple version you compare improvements against.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
boilerplate
Standard text repeated on every article, not real content.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
cauda equina
Nerve roots at the base of the spine; pressure on them is an emergency.Used in: How it's tested↩ Back to where you were
Chroma
The database that stores the policy vectors.Used in: ServiceApps example: the same ingestion for KB articles, Words used in this post, How ingestion flows, Sub-step 7: Embed, Sub-step 8: Store in Chroma, Interview answer↩ Back to where you were
chunk
A small piece of a document; here, one policy rule.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, Why we ingest this way, See it: one policy, cut two ways, Words used in this post, How ingestion flows, Sub-step 3: Find the clauses, Sub-step 4: Add header, ID and metadata, Sub-step 5: Split long clauses, Sub-step 6: Flag injection-like text, Sub-step 7: Embed, Sub-step 8: Store in Chroma, How it's tested, Checklist: what is done and what is next, Interview answer, What this proves↩ Back to where you were
chunks
Small pieces of a document; here, one policy rule each.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, Why we ingest this way, See it: one policy, cut two ways, Words used in this post, How ingestion flows, Sub-step 2: Read the pages, Sub-step 3: Find the clauses, Sub-step 4: Add header, ID and metadata, Sub-step 6: Flag injection-like text, Sub-step 7: Embed, Sub-step 8: Store in Chroma, How it's tested, Checklist: what is done and what is next, Honest gaps, Interview answer↩ Back to where you were
citation
A pointer to the exact page and quote that supports a claim.Used in: What this proves↩ Back to where you were
citations
Pointers to the exact page and quote that support each claim.Used in: ServiceApps example: the same ingestion for KB articles, Sub-step 2: Read the pages↩ Back to where you were
Claude
Anthropic's AI model that this app uses.Used in: Sub-step 4: Add header, ID and metadata, Sub-step 6: Flag injection-like text, Sub-step 7: Embed↩ Back to where you were
clause
One rule in a policy, such as §2.A.Used in: Words used in this post, How ingestion flows, Sub-step 3: Find the clauses, Sub-step 4: Add header, ID and metadata, Sub-step 5: Split long clauses, How it's tested, Checklist: what is done and what is next, Honest gaps, Interview answer↩ Back to where you were
CLI
Command-line tool: commands typed in a terminal.Used in: Sub-step 6: Flag injection-like text↩ Back to where you were
collection
A named group of stored chunks inside Chroma, like a table.Used in: Sub-step 8: Store in Chroma↩ Back to where you were
content hash
A fingerprint of a file that changes whenever the file changes.Used in: ServiceApps example: the same ingestion for KB articles, Checklist: what is done and what is next, Honest gaps, What this proves↩ Back to where you were
contextual header
The label at the top of each chunk: policy, version, CPT code, section and page.Used in: ServiceApps example: the same ingestion for KB articles, Words used in this post, How ingestion flows↩ Back to where you were
contextual retrieval
Adding a short summary of the whole document to each chunk before embedding.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
contrast
Dye given during a scan to show some tissues better.Used in: Sub-step 3: Find the clauses↩ Back to where you were
cosine similarity
A score from -1 to 1 for how close two meanings are.Used in: Sub-step 7: Embed↩ Back to where you were
CPT
A standard code for a medical procedure.Used in: How ingestion flows, Sub-step details: one policy all the way through, Sub-step 8: Store in Chroma, How it's tested, Checklist: what is done and what is next↩ Back to where you were
CPT code
A standard code for a medical procedure.Used in: Why this post, Why we ingest this way, See it: one policy, cut two ways, Words used in this post, Sub-step 1: Find the policy file, Sub-step 8: Store in Chroma, Interview answer↩ Back to where you were
Docling
An open-source library that converts documents into structured text.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
dot product
Multiply two lists of numbers pair by pair and add the results.Used in: Sub-step 7: Embed↩ Back to where you were
embedded
Turned into numbers (a vector) so similar meanings sit close together.Used in: Why this post, Sub-step 4: Add header, ID and metadata, Sub-step 5: Split long clauses↩ Back to where you were
embedding
Text turned into numbers so similar meanings sit close together.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, Words used in this post, Sub-step 7: Embed↩ Back to where you were
embeddings
Text turned into numbers so similar meanings sit close together.Used in: Words used in this post, Sub-step 8: Store in Chroma↩ Back to where you were
evals
Graded tests of the AI's answers, scored against an answer key.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
expedited review
A fast review, within 72 hours, when waiting could harm the member.Used in: Sub-step 3: Find the clauses↩ Back to where you were
fallback
The backup method used only when the main one can't work.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, See it: one policy, cut two ways, Sub-step 5: Split long clauses↩ Back to where you were
fixed-size
Cutting text every N characters, wherever that lands.Used in: ServiceApps example: the same ingestion for KB articles, See it: one policy, cut two ways, Checklist: what is done and what is next, Honest gaps, Interview answer↩ Back to where you were
Fly.io
The cloud service that hosts the live app.Used in: Sub-step 7: Embed↩ Back to where you were
health plan
The insurer that pays for members' care.Used in: Why we ingest this way↩ Back to where you were
hit@1
The right section came back first.Used in: ServiceApps example: the same ingestion for KB articles, Honest gaps↩ Back to where you were
HTML
The markup language web pages are written in.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
incident
A ServiceApps ticket for something broken.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
index
The searchable store of chunks and their vectors.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, See it: one policy, cut two ways, Words used in this post, How ingestion flows, Sub-step 6: Flag injection-like text, How it's tested, Honest gaps, Interview answer↩ Back to where you were
ingestion
Preparing documents ahead of time: cut into chunks, tagged and stored for search.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, Words used in this post, How ingestion flows, How it's tested, Honest gaps, What this proves↩ Back to where you were
injection
Hidden text that tries to give the AI new orders.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
input guardrails
Checks that block tricks, off-topic and secret-looking input before the AI sees it.Used in: Sub-step 6: Flag injection-like text↩ Back to where you were
JSON
A simple text format for structured data.Used in: Sub-step 1: Find the policy file↩ Back to where you were
KB
Knowledge base: a library of help articles.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
KB article
One help-center article in a knowledge base, with a number like KB0010234.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
keyword search
Search for the exact words in the question.Used in: Sub-step 7: Embed↩ Back to where you were
knowledge base
A library of help articles; in ServiceApps, a named group of KB articles.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
late chunking
Embedding a whole document first, then splitting the result into chunks.Used in: ServiceApps example: the same ingestion for KB articles, See it: one policy, cut two ways↩ Back to where you were
layout-aware parsing
Reading a file's layout (bold headings, lists, tables) to find its structure.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
live
Using the real Claude API (costs money), not a fake stand-in.Used in: ServiceApps example: the same ingestion for KB articles, Sub-step 1: Find the policy file↩ Back to where you were
lumbar
The lower back.Used in: Sub-step 3: Find the clauses, Sub-step 5: Split long clauses↩ Back to where you were
medical policy
A health plan's written rules for when a procedure is covered.Used in: Why we ingest this way↩ Back to where you were
meniscus
The cartilage cushion inside the knee.Used in: Why this post, Why we ingest this way↩ Back to where you were
metadata
Labels stored with each chunk: policy, CPT, version, section, page.Used in: ServiceApps example: the same ingestion for KB articles, Sub-step 4: Add header, ID and metadata, Interview answer↩ Back to where you were
MRI
A scan that uses magnets to show soft tissue like discs, ligaments and the brain.Used in: Why we ingest this way, Words used in this post, Sub-step details: one policy all the way through, Sub-step 3: Find the clauses, Sub-step 4: Add header, ID and metadata, Honest gaps↩ Back to where you were
MRR
A score for how high the right section ranks: 1st = 1, 2nd = 0.5, 3rd = 0.33.Used in: ServiceApps example: the same ingestion for KB articles, Honest gaps↩ Back to where you were
normalized
Scaled to length 1, so similarity is a simple multiply-and-add.Used in: Sub-step 7: Embed, Sub-step 8: Store in Chroma↩ Back to where you were
Now Assist
ServiceApps's built-in generative AI features.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
nurse
The reviewer who checks requests; can approve or pend, not deny.Used in: Why we ingest this way, See it: one policy, cut two ways, Sub-step 4: Add header, ID and metadata↩ Back to where you were
OCR
Reading the text in a picture of a page, like a fax.Used in: Sub-step 2: Read the pages↩ Back to where you were
osteoarthritis
Wear-and-tear arthritis.Used in: Sub-step 3: Find the clauses↩ Back to where you were
output checks
Code that verifies the AI's answer, such as every quote really being in the source.Used in: See it: one policy, cut two ways, Sub-step 4: Add header, ID and metadata, Sub-step 6: Flag injection-like text↩ Back to where you were
overlap
Characters repeated between neighboring chunks so nothing is lost at a cut.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, How ingestion flows, Sub-step 5: Split long clauses, Interview answer↩ Back to where you were
page furniture
Text repeated on every page, like headers and footers, that isn't content.Used in: ServiceApps example: the same ingestion for KB articles, Words used in this post, How ingestion flows, Sub-step 2: Read the pages, How it's tested↩ Back to where you were
parent–child
Search small chunks, then give the AI the bigger section they came from.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
PDF
A fixed-layout document file.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, Why we ingest this way, See it: one policy, cut two ways, How ingestion flows, Sub-step 1: Find the policy file, Sub-step 2: Read the pages, Sub-step 3: Find the clauses, Sub-step 4: Add header, ID and metadata, How it's tested, Interview answer↩ Back to where you were
pipeline
The series of steps a request goes through.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
policies
The health plan's written rules for when tests are covered.Used in: ServiceApps example: the same ingestion for KB articles, See it: one policy, cut two ways, Sub-step 1: Find the policy file, Sub-step 2: Read the pages, Sub-step 3: Find the clauses, Sub-step 5: Split long clauses, How it's tested, Checklist: what is done and what is next, Interview answer, What this proves↩ Back to where you were
policy
The health plan's written rules for when a test is covered.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, Why we ingest this way, See it: one policy, cut two ways, Words used in this post, How ingestion flows, Sub-step details: one policy all the way through, Sub-step 1: Find the policy file, Sub-step 2: Read the pages, Sub-step 3: Find the clauses, Sub-step 4: Add header, ID and metadata, Sub-step 5: Split long clauses, Sub-step 6: Flag injection-like text, Sub-step 7: Embed, Sub-step 8: Store in Chroma, How it's tested, Honest gaps, Interview answer, What this proves↩ Back to where you were
prior authorization
A health plan approving a test or treatment before it happens.Used in: Why we ingest this way↩ Back to where you were
prompt
The instructions and text given to the AI.Used in: Sub-step 6: Flag injection-like text↩ Back to where you were
prompt injection
Hidden text that tries to give the AI new orders.Used in: Sub-step 6: Flag injection-like text↩ Back to where you were
proposition
A single standalone fact rewritten by an AI from the text.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
pypdf
A library that reads text from PDFs.Used in: ServiceApps example: the same ingestion for KB articles, Sub-step 2: Read the pages↩ Back to where you were
query rewriting
Restating a question in the policy's own wording before searching.Used in: Sub-step 7: Embed↩ Back to where you were
RAG
Retrieval-augmented generation: the AI looks things up before it answers.Used in: ServiceApps example: the same ingestion for KB articles, Why we ingest this way, Sub-step 7: Embed↩ Back to where you were
re-index
Rebuild the searchable store after documents change.Used in: Words used in this post, Checklist: what is done and what is next, Honest gaps, Interview answer↩ Back to where you were
re-ranking
A second model reorders the top results.Used in: Sub-step 7: Embed↩ Back to where you were
read the request
Reading the incoming request's pages, finding its CPT code and scanning it for tricks.Used in: ↩ Back to where you were
recursive split
Splitting text by paragraph, then line, then sentence, until each piece fits.Used in: Interview answer↩ Back to where you were
recursive splitter
Code that splits text by paragraph, then line, then sentence, until each piece fits.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
regex
Short for regular expression: a text pattern the code matches.Used in: Words used in this post↩ Back to where you were
registry
The small JSON file listing each policy's CPT code, file, number and version.Used in: How ingestion flows, Sub-step 1: Find the policy file↩ Back to where you were
regular expression
A text pattern the code matches, like 'a number, a dot, then words'.Used in: Words used in this post, Sub-step 3: Find the clauses↩ Back to where you were
REST
A common way for programs to talk over the web using URLs.Used in: Why this post, ServiceApps example: the same ingestion for KB articles, Sub-step 3: Find the clauses, Sub-step 5: Split long clauses↩ Back to where you were
retired
Taken out of use; a retired article no longer shows to readers.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
retrieval
Finding the right section of the right policy.Used in: Honest gaps↩ Back to where you were
saddle numbness
Numbness around the groin and buttocks, a warning sign.Used in: How it's tested↩ Back to where you were
semantic chunking
Cutting text where the meaning changes.Used in: ServiceApps example: the same ingestion for KB articles, See it: one policy, cut two ways↩ Back to where you were
sentence window
Store single sentences and return each with its neighbors.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
ServiceApps
A company platform for IT tickets, HR requests and help-center articles.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
SharePoint
Microsoft's document and intranet platform.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
synthetic
Made up for the demo; no real patients.Used in: Sub-step details: one policy all the way through, Sub-step 2: Read the pages, Sub-step 3: Find the clauses, What this proves↩ Back to where you were
system prompt
The standing instructions that set the AI's rules and role.Used in: Sub-step 6: Flag injection-like text↩ Back to where you were
Table API
ServiceApps's standard web API for reading table records.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
threshold
The cut-off a score must stay above.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
traces
Step-by-step records of each request: what ran, how long, what it cost.Used in: Sub-step 4: Add header, ID and metadata↩ Back to where you were
unit test
A small automatic check of one piece of code.Used in: Sub-step 5: Split long clauses↩ Back to where you were
unit tests
Small automatic checks of one piece of code each.Used in: ↩ Back to where you were
Unstructured
An open-source library that reads PDFs and Word files into headings, lists and tables.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
user criteria
ServiceApps's rules for who may read an article.Used in: ServiceApps example: the same ingestion for KB articles↩ Back to where you were
vector store
A database that finds text by meaning, using embeddings.Used in: Words used in this post↩ Back to where you were
vectors
Text turned into lists of numbers so similar meanings sit close together.Used in: Sub-step 7: Embed, Sub-step 8: Store in Chroma↩ Back to where you were
virtual environment
A project's own folder of Python libraries.Used in: Try it yourself↩ Back to where you were
word-pieces
The small word parts a model reads; a long word may be several.Used in: Why this post, Sub-step 5: Split long clauses↩ Back to where you were
X-ray
A quick image that shows bones.Used in: See it: one policy, cut two ways↩ Back to where you were