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
- Why this post: what this deep dive covers, and how cutting by structure differs from cutting by characters
- 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)
- 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
- Words used in this post: the terms
- How ingestion flows: the 8 sub-steps in the order the code runs them
- Sub-step details: the real code and real output for each one
- Try it yourself: commands to run it on your machine
- How it's tested: the unit tests (small automatic checks of one piece of code each) and today's result
- Checklist and Honest gaps: what is done, and what isn't measured or isn't true yet
- 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:
- 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.
- 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.
- 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:
- The limit comes from the model, not the policy (the health plan's written rules for when a test is covered). The embedding (text turned into numbers so similar meanings sit close together) model (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, and silently ignores the rest (a common way for programs to talk over the web using URLs). A rule longer than that would be only partly embedded (turned into numbers (a vector) so similar meanings sit close together), and its end could never be found. So characters cap the size, but they never pick the boundary.
- Splitting at a break beats splitting at a count. When a split is needed, a paragraph or sentence break keeps whole thoughts together, and the overlap (characters repeated between neighboring chunks so nothing is lost at a cut) means a sentence crossing the cut appears whole in at least one piece.
- Today the safety net never fires. The longest of the 83 chunks (small pieces of a document; here, one policy rule each) is 487 characters, so every chunk (a small piece of a document; here, one policy rule) in the index (the searchable store of chunks and their vectors) is exactly one rule. The net is there for a future policy (the health plan's written rules for when a test is covered) with a very long rule.
What we added to this idea:
- There is no minimum size. Character-based chunking usually also merges small pieces to reach a target size. We don't: the shortest rule (§2.D Planning for knee surgery, 132 characters with its header) stays its own chunk (a small piece of a document; here, one policy rule). Merging it into its neighbor would mix two rules, and the AI could cite the wrong one. The header gives a short chunk (a small piece of a document; here, one policy rule) the context its body lacks.
- No overlap (characters repeated between neighboring chunks so nothing is lost at a cut) between rules. Character chunking repeats text between neighboring pieces (often 10–20%) to patch cuts that land mid-sentence. Our cuts land where a rule ends, so there is nothing to patch, and the chunks (small pieces of a document; here, one policy rule each) don't overlap (characters repeated between neighboring chunks so nothing is lost at a cut) at all. Adding overlap (characters repeated between neighboring chunks so nothing is lost at a cut) here would do harm: the end of §2.A would appear inside §2.B's chunk (a small piece of a document; here, one policy rule), so a search could return §2.B for a question about §2.A, and the AI could cite the wrong section. The only overlap (characters repeated between neighboring chunks so nothing is lost at a cut) is the 150 characters between pieces of one long rule when the fallback (the backup method used only when the main one can't work) splits it, and it never crosses into another rule.
- The cut decides what can be cited. The AI must quote a rule and give its § and page, and a later step matches every quote against the PDF (a fixed-layout document file). With character cuts, a chunk (a small piece of a document; here, one policy rule) could start in §2.A and end in §2.B, so no single § or page would be true for it. With structure cuts, every chunk (a small piece of a document; here, one policy rule) has exactly one § and one page.
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 article | Domain article | |
|---|---|---|
| Example | KB0010234 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 as | Symptoms, Applies to, numbered Steps, an error-code table, Related articles | Numbered 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) cuts | Steps 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 fix | The 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-step | NurseOps Now (PDF files) | ServiceApps (KB articles) |
|---|---|---|---|
| 1 | Find the source | policies/index.json lists each file, number and version | REST (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) |
| 2 | Read the content | pypdf (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) |
| 3 | Find the units | Numbered 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 |
| 4 | Header + metadata (labels stored with each chunk: policy, CPT, version, section, page) | Document number, version, section and page | 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, 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)) |
| 5 | Split long sections | 1,200-character fallback (the backup method used only when the main one can't work) at natural breaks | Same; long troubleshooting sections are common |
| 6 | Flag injection (hidden text that tries to give the AI new orders) | Pattern check on the text | Same, 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) |
| 7 | Embed | all-MiniLM-L6-v2 (a small, free open model that turns text into 384 numbers), local | Same model, or a larger one for thousands of articles |
| 8 | Store | Delete the document's old chunks (small pieces of a document; here, one policy rule each), then add | Delete 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
Article 2 (domain: HR policy): KB0020311 Remote work policy → 6 chunks
What to notice:
- One article, many chunks (small pieces of a document; here, one policy rule each). The chunk (a small piece of a document; here, one policy rule) "Error 809" is one of 6 chunks (small pieces of a document; here, one policy rule each) from the VPN article, and "4. Working from another country" is one of 6 from the remote work policy (the health plan's written rules for when a test is covered). A question finds the one chunk (a small piece of a document; here, one policy rule) that answers it, not the whole article.
- The tech article is cut by its parts. Symptoms, Applies to and Steps are one chunk (a small piece of a document; here, one policy rule) each, and all 6 steps stay together. The error-code table becomes one chunk (a small piece of a document; here, one policy rule) per row, so "error 812" finds only its own fix.
- The domain article is cut by its numbered rules. Each rule keeps its exceptions with it, so rule 4's "up to 10 days" never gets separated from "longer stays need approval".
- Not everything is kept. The "Internal" banner and "Was this article helpful?" are template text in every article, so they're thrown away. Related articles is only links, with no answer in it, so it's skipped too. The Error codes heading has no text of its own, so it isn't a chunk (a small piece of a document; here, one policy rule); its rows are.
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 like | Best strategy | Overlap? |
|---|---|---|
| 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 article | Recursive 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 characters | Yes, about 10–15% (100–150 characters), because cuts can land mid-thought |
| Mixed: some headings, but some sections are very long | Structure first, then the recursive splitter (code that splits text by paragraph, then line, then sentence, until each piece fits) inside each long section | Only 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:
| Rank | Strategy | How it cuts | Best for | Pro | Con |
|---|---|---|---|---|---|
| 1st | 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) | 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 default | Cheap, predictable, works on any text | Doesn't know where an idea ends, so overlap (characters repeated between neighboring chunks so nothing is lost at a cut) patches the cuts |
| 2nd | Layout-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 title | Attached 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 whole | Heavier and slower, sometimes a paid service; can misread messy files |
| 3rd | Semantic chunking (cutting text where the meaning changes) (LangChain SemanticChunker, LlamaIndex semantic splitter) | Embeds every sentence and cuts where neighbors stop being similar | Long free text that changes topic: meeting notes, email threads | Chunks (small pieces of a document; here, one policy rule each) follow topics, not character counts | An 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:
- Contextual headers (the label at the top of each chunk: policy, version, CPT code, section and page): the
[KB number | knowledge base | category | title | section]line above, or a one-line summary of the whole article added to each chunk (a small piece of a document; here, one policy rule) (often called contextual retrieval (adding a short summary of the whole document to each chunk before embedding)). Helps every splitter. - Parent–child (search small chunks, then give the AI the bigger section they came from) ("small-to-big"): search small chunks (small pieces of a document; here, one policy rule each) for precision, then give the AI the larger section they came from.
- Sentence window (store single sentences and return each with its neighbors): store single sentences, and return each one with its neighbors.
- Late chunking (embedding a whole document first, then splitting the result into chunks): embed the whole article with a long-context model first, then split, so each chunk (a small piece of a document; here, one policy rule) "knows" the rest (a common way for programs to talk over the web using URLs). Needs special models.
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:
- Template with headings → structure first.
- Visual headings in attached files → layout-aware parsing (reading a file's layout (bold headings, lists, tables) to find its structure).
- 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.
- 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).
- 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):
- Permissions. KB articles (one help-center article in a knowledge base, with a number like KB0010234) have read rules (user criteria (ServiceApps's rules for who may read an article)). An assistant must never show a chunk (a small piece of a document; here, one policy rule) the user can't open in ServiceApps (a company platform for IT tickets, HR requests and help-center articles). Store who may read each article, filter search results by it, or check access through ServiceApps (a company platform for IT tickets, HR requests and help-center articles) with the user's own login before showing an answer.
- Lifecycle. Articles move through draft, review, published and retired (taken out of use; a retired article no longer shows to readers). 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 expires (
valid_to). - Change detection is the norm. A KB (knowledge base: a library of help articles) can hold thousands of articles that change daily, so re-embedding everything each time isn't an option. A content hash (a fingerprint of a file that changes whenever the file changes) per article (which NurseOps Now doesn't have yet; see Honest gaps) is required here.
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)
- "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_knowledgethrough 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." - "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'."
- "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_idfirst 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." - "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)."
- "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
2. Cut by structure (what NurseOps Now does): pages 1–2 become 8 chunks
3. Cut every 500 characters (the common way): the same text becomes 3 pieces
What to notice:
- Where the cuts are. In picture 2 every cut sits on the policy (the health plan's written rules for when a test is covered)'s own numbering (1, 2.A, 2.B … 5). In picture 3 the cuts sit wherever character 500 and 1,000 land, and the first one splits "X-ray (a quick image that shows bones)" into "X-r ✂ ay".
- One rule per box vs. many. Each chunk (a small piece of a document; here, one policy rule) in picture 2 holds exactly one rule, with one § and one page. Piece 1 in picture 3 holds §1, the §2 heading, all of §2.A and half of §2.B. Piece 2 runs from the second half of §2.B to the start of §5.
- The header. Every chunk (a small piece of a document; here, one policy rule) in picture 2 starts with a bold
[…]line the code adds (policy (the health plan's written rules for when a test is covered), version, CPT code (a standard code for a medical procedure), §, page). The pieces in picture 3 have none, so piece 2 begins "ay first to rule out fracture" with no hint of where it came from. - Small rules stay small. Chunk (a small piece of a document; here, one policy rule) 5 (§2.D, 132 characters) stays its own chunk (a small piece of a document; here, one policy rule). Character cutting would always glue it to its neighbors.
- The heading that isn't a chunk (a small piece of a document; here, one policy rule). The §2 heading has no text of its own, so it isn't stored alone. Its title is copied into the headers of 2.A–2.D instead (the dashed box in picture 2).
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
| Term | Plain meaning | Everyday example |
|---|---|---|
| Ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) | Preparing documents ahead of time so they can be searched | Shelving 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) rule | One 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.A | One 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 page | The 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 content | The 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 together | Placing 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 changes | Reprinting 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 knee | A 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-step | What happens | Code | Checked by |
|---|---|---|---|---|
| 1 | Find the policy file | Look 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, version | services/policy.py registry(), policy_path() | test_unknown_cpt_is_404 |
| 2 | Read the pages | Extract 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)) |
| 3 | Find the clauses | Walk 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 |
| 4 | Add header, ID and metadata | Prefix 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 labels | chunker.py chunk_policy() | test_metadata_on_every_chunk |
| 5 | Split long clauses | Only 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 |
| 6 | Flag injection-like text | Mark chunks (small pieces of a document; here, one policy rule each) that look like hidden instructions and keep them out | chunker.py INJECTION, index.py index_policy() | test_injection_like_text_is_flagged |
| 7 | Embed | Turn 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 SentenceTransformerEmbedder | offline HashEmbedder in tests |
| 8 | Store in Chroma | Delete 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 ones | index.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.
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.
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 ID | Label | Section | Page | Characters |
|---|---|---|---|---|
73721-v2.2-1 | §1 | Purpose | 1 | 139 |
73721-v2.2-2.A | §2.A | Covered when ONE of the following is documented | 1 | 355 |
73721-v2.2-2.B | §2.B | Covered when ONE of the following is documented | 1 | 233 |
73721-v2.2-2.C | §2.C | Covered when … | 1 | 150 |
73721-v2.2-2.D | §2.D | Covered when … | 1 | 132 |
73721-v2.2-3 | §3 | Required documentation | 2 | 233 |
73721-v2.2-4 | §4 | Not medically necessary | 2 | 235 |
73721-v2.2-5 | §5 | Review | 2 | 230 |
73721-v2.2-6.A … 6.D | §6.A–D | Definitions | 3 | 155–232 |
73721-v2.2-7.A, 7.B | §7.A–B | Repeat knee MRI (a scan that uses magnets to show soft tissue like discs, ligaments and the brain) | 3 | 163–165 |
73721-v2.2-8.A … 8.C | §8.A–C | Post-operative imaging | 3 | 143–217 |
73721-v2.2-9 … 10 | §9, §10 | Prior imaging, Contrast (dye given during a scan to show some tissues better) | 4 | 215–308 |
73721-v2.2-11.A … 11.C | §11.A–C | Special populations | 4 | 160–224 |
73721-v2.2-12 | §12 | Osteoarthritis (wear-and-tear arthritis) | 4 | 241 |
73721-v2.2-13 … 18 | §13–§18 | Expedited 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, history | 5 | 216–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).
What to notice in the whole document:
- Every page starts clean. Each page starts with 4 header lines (plan name, two "synthetic (made up for the demo; no real patients)" banners, and the policy (the health plan's written rules for when a test is covered) title with that page's topic), and the code throws them all away: 23 lines in total, counting the 3 extra policy-detail lines on page 1.
- 29 chunks (small pieces of a document; here, one policy rule each), 5 headings. §2, §6, §7, §8 and §11 have lettered rules under them, so the headings aren't chunks (small pieces of a document; here, one policy rule each); each letter is. The other 13 sections have no letters, so each whole section is one chunk (a small piece of a document; here, one policy rule).
- No chunk (a small piece of a document; here, one policy rule) crosses a page. Each page starts with a new section, so every chunk (a small piece of a document; here, one policy rule) has exactly one page number to cite.
- Sizes vary, on purpose. The smallest chunk (a small piece of a document; here, one policy rule) is 132 characters (§2.D) and the largest is 355 (§2.A). The cut follows the rule, not a target size.
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.
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:
- The header is part of the text, so it is embedded (turned into numbers (a vector) so similar meanings sit close together) too. A search for "knee MRI (a scan that uses magnets to show soft tissue like discs, ligaments and the brain) coverage" is pulled toward knee chunks (small pieces of a document; here, one policy rule each) even when the rule body never says "knee". A nurse (the reviewer who checks requests; can approve or pend, not deny) or Claude (Anthropic's AI model that this app uses) reading the chunk (a small piece of a document; here, one policy rule) alone knows whose rule it is.
- The metadata (labels stored with each chunk: policy, CPT, version, section, page) is for code. Search filters on
cptso a knee question never returns a spine rule. The review citeslabelandpage. The audit trail (the record of who did what, when, kept for review) storesversion. - The quote leaves the header out.
body_of()strips the header, so the quote that output checks (code that verifies the AI's answer, such as every quote really being in the source) match against the PDF (a fixed-layout document file) is the policy (the health plan's written rules for when a test is covered)'s real wording:
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.
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.
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".
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.
- Local and free: no API cost per chunk (a small piece of a document; here, one policy rule), no policy (the health plan's written rules for when a test is covered) text sent out to embed, and it runs offline.
- Normalized (scaled to length 1, so similarity is a simple multiply-and-add) vectors (text turned into lists of numbers so similar meanings sit close together) (
normalize_embeddings=True), so cosine similarity (a score from -1 to 1 for how close two meanings are) is a plain dot product (multiply two lists of numbers pair by pair and add the results) and Chroma (the database that stores the policy vectors)'s cosine distance matches it. - Small and fast: 384 numbers per chunk (a small piece of a document; here, one policy rule), 83 chunks (small pieces of a document; here, one policy rule each) in total. A larger model would cost more memory on the Fly.io (the cloud service that hosts the live app) machine for little gain at this size. Part C of the eval plan is where a model comparison would go.
- Tests never download it. They swap in
HashEmbedder, a tiny word-counting embedder, throughset_embedder(), so the 11 RAG (retrieval-augmented generation: the AI looks things up before it answers) tests run offline in about a second.
In plain terms: giving every card a map coordinate so cards about the same thing sit close together.
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.
- Delete, then add, per CPT code (a standard code for a medical procedure). Re-indexing twice gives the same 83 chunks (small pieces of a document; here, one policy rule each), never 166 duplicates (tested). When a policy (the health plan's written rules for when a test is covered) moves from v2.2 to v2.3, all v2.2 chunks (small pieces of a document; here, one policy rule each) go and only v2.3 remains, so search can't mix two versions of the same rule.
embedding_function=None. Chroma (the database that stores the policy vectors) would otherwise quietly embed with its own default model. Passing embeddings (text turned into numbers so similar meanings sit close together) in makes sure the same model embeds the chunks (small pieces of a document; here, one policy rule each) and the questions.- Cosine space, to match the normalized (scaled to length 1, so similarity is a simple multiply-and-add) vectors (text turned into lists of numbers so similar meanings sit close together) from sub-step 7.
- One collection (a named group of stored chunks inside Chroma, like a table), filtered by CPT (a standard code for a medical procedure). Every search passes
where={"cpt": ...}, so it only looks at the one policy (the health plan's written rules for when a test is covered) for the procedure on the request (8 to 29 chunks (small pieces of a document; here, one policy rule each)), not all 83.
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.
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.
| Test | What it proves |
|---|---|
test_clause_aware_chunks_one_per_criterion_with_header | Each 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_chunk | Every 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_clauses | A 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_duplicates | Indexing twice gives the same count, with no duplicates |
test_search_builds_index_on_first_use | An empty index (the searchable store of chunks and their vectors) is built automatically on the first search |
test_search_is_filtered_to_the_cpt_policy | A 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
| Item | Status | Result |
|---|---|---|
| Clause-aware chunks with headers | ✅ Done | 83 chunks (small pieces of a document; here, one policy rule each), one rule each |
| Metadata for filter, cite and audit | ✅ Done | CPT (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 yet | Longest chunk (a small piece of a document; here, one policy rule) today: 487 characters |
| Injection flag at ingestion | ✅ Done | 0 of 83 flagged |
| Re-index without duplicates | ✅ Done | Tested |
| 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 do | Eval 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 built | See Honest gaps |
Honest gaps
- The clause (one rule in a policy, such as §2.A) choice isn't measured yet. The fixed-size (cutting text every N characters, wherever that lands) example above shows a rule cut in half, but there is no score yet saying how much clause (one rule in a policy, such as §2.A) chunks (small pieces of a document; here, one policy rule each) improve search. Part C of the eval plan runs the same questions with fixed-size (cutting text every N characters, wherever that lands) chunks (small pieces of a document; here, one policy rule each) and with clause (one rule in a policy, such as §2.A) chunks (small pieces of a document; here, one policy rule each) and reports 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) for both.
- There is no content hash (a fingerprint of a file that changes whenever the file changes) today. The feature blog says "a content hash (a fingerprint of a file that changes whenever the file changes) re-indexes (rebuild the searchable store after documents change) only the files that changed". The code doesn't do that:
index-policiesre-reads and re-embeds every policy (the health plan's written rules for when a test is covered) (83 chunks (small pieces of a document; here, one policy rule each), a few seconds), and a search rebuilds the index (the searchable store of chunks and their vectors) only when it is empty. Each policy (the health plan's written rules for when a test is covered) is replaced as a whole, so there are no stale duplicates, but nothing detects which file changed. Either the code needs a hash per file, or the feature blog needs correcting. - Only the newest version is searchable. Re-indexing deletes every older version of a policy (the health plan's written rules for when a test is covered). Reviews store the chunks (small pieces of a document; here, one policy rule each) and version they used, so past decisions stay auditable, but a case can't be re-run against last year's version.
- One known retrieval (finding the right section of the right policy) miss starts here. In Step 0, "What documents are required for a knee MRI (a scan that uses magnets to show soft tissue like discs, ligaments and the brain)?" returned §17 Coding notes instead of §3 Required documentation. Both chunks (small pieces of a document; here, one policy rule each) are short and both mention requests and documents. Whether the fix belongs in ingestion (preparing documents ahead of time: cut into chunks, tagged and stored for search) (for example, adding the section title to the keyword index (the searchable store of chunks and their vectors) more strongly) or in search is a question for Part C.
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
- 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
- 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