Extract · Letters
Log who an FDA warning letter went to, from which office and when
A compliance team that follows FDA warning letters wants a row for each: the date, the office that issued it, the company it went to. The letters run to five to eight thousand characters of legal prose. Nenya reads the whole letter and returns the three facts. This is the hardest of our four sources, and the cookbook is honest about it: two fields are reliable, one is not, and a rule of three lines fixes most of what the model misses.
- The move
- Pull a few facts out of a long formal letter, and patch the one the model misses with a rule.
- The model’s role
- It reads the letter. Your code checks the result and handles the cases that follow a pattern.
- Why it fits
- The date and the office are written a dozen ways (“CBER”, “the Center for Tobacco Products of the U.S. Food and Drug Administration”). The model normalises them. The addressee of half of these letters is a website, which is a pattern, and patterns are for code.
- How it goes
- Letter in → the field list and the whole letter → one record → a rule for letters “To Whom It May Concern” → store.
- Payoff
- Measured: on 22 real letters the date was right in 22 and the issuing office in 21. The addressee was right in 9 from the model alone and in 21 with the rule. On all 125 letters of our test set, each asked for its own list of fields, 78.4 field F1. About 1,600 tokens a letter.
On this page
The data#
Warning letters that the US Food and Drug Administration (FDA) published in 2026. They are public-domain documents. Each comes with the values of FDA’s own listing of the letter: those are the answers. They are a test set: the model has no training data for them.
Four fields. The last, the establishment number, is one these letters do not state, so the right answer for it is null:
- recipient_company (string): Name of the company the letter is addressed to
- issuing_office (string): FDA office or center that issued the letter
- letter_date (string): Date the letter was issued, YYYY-MM-DD
- fei_number (string): FDA Establishment Identifier (FEI number) of the facilitySet up#
pip install openai. The API is free and needs no key.
import json
import re
import textwrap
from pathlib import Path
from openai import OpenAI
client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")The recipe#
The extract function of the API page, unchanged.
def extract(kind, document, fields, max_tokens=800):
"""{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
f"Fields:\n{lines}\n\n"
"Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
"additionalProperties": False}
reply = client.chat.completions.create(
model="nenya",
messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
temperature=0, # one right answer: do not sample
max_tokens=max_tokens,
response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
)
choice = reply.choices[0]
if choice.finish_reason != "stop": # "length": the JSON was cut off and will not parse
raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
return json.loads(choice.message.content)DATA = json.loads((Path(__file__).parent / "data" / "extract-warning-letters.json").read_text())
KIND = DATA["kind"] # "FDA warning letter"
FIELDS = DATA["fields"]
for field in FIELDS:
print(f"- {field['name']} ({field['type']}): {field['description']}")The request#
The whole letter goes in. Only its beginning is printed here:
letter = DATA["examples"][0]
print(textwrap.fill(letter["document"][:560], 100))
print(f"[... {len(letter['document']) - 560:,} more characters]")
record = extract(KIND, letter["document"], FIELDS)
print()
print(json.dumps(record, indent=2))The response#
March 31, 2026 WARNING LETTER To Whom It May Concern: The Center for Tobacco Products of the U.S.
Food and Drug Administration (FDA) recently reviewed our inspection records and determined that
Global Tobacco, LLC imports, sells and/or distributes nicotine pouch products to customers in the
United States. Under section 201(rr) of the Federal Food, Drug, and Cosmetic Act (FD&C Act) (21
U.S.C. § 321(rr)), these products are tobacco products because they are made or derived from tobacco
or contain nicotine from any source and intended for human consumpt
[... 6,251 more characters]
{
"recipient_company": "Global Tobacco, LLC",
"issuing_office": "Center for Tobacco Products",
"letter_date": "2026-03-31",
"fei_number": null
}“March 31, 2026” came back as 2026-03-31. The office is named in the middle of the first sentence, the company a line later.
Check it#
def same(value, answer):
"""Is an extracted value the right one? Text is compared by its letters and digits (case, spaces and
punctuation aside), numbers as numbers, and a field the document does not state has to be null."""
if value is None or answer is None:
return value is None and answer is None
if isinstance(answer, (int, float)):
return isinstance(value, (int, float)) and value == answer
squeeze = lambda s: "".join(c for c in str(s).casefold() if c.isalnum()) # noqa: E731
return squeeze(value) == squeeze(answer)
for name, value in record.items():
verdict = "right" if same(value, letter["answer"][name]) else f"WRONG, FDA has {letter['answer'][name]!r}"
print(f"{name:<18} {value!r:<30} {verdict}")recipient_company 'Global Tobacco, LLC' right
issuing_office 'Center for Tobacco Products' right
letter_date '2026-03-31' right
fei_number None rightThree letters#
for letter in DATA["examples"]:
record = extract(KIND, letter["document"], FIELDS)
print(f"{record['letter_date']} {record['issuing_office']:<40} {record['recipient_company']:<22} FEI {record['fei_number']}")2026-03-31 Center for Tobacco Products Global Tobacco, LLC FEI None
2026-06-17 Center for Drug Evaluation and Research Texinkart Inc. FEI None
2026-05-22 Center for Tobacco Products UPROAR WELLNESS LLC FEI NoneAll three rows are FDA’s, field for field.
A letter about a website#
Twelve of the 22 letters are not addressed to a company. FDA reviewed a website, found no name behind it, and wrote “To Whom It May Concern”. Its listing files such a letter under the website. Asked for “the company the letter is addressed to”, the model does not answer with the website:
def addressee(letter, record):
"""Who an FDA warning letter is addressed to. A letter about a website opens "To Whom It May Concern" and names
no company, and the model then gives the FDA office that wrote it or another name in the letter. For those,
take the website out of the text."""
site = re.search(r"reviewed the (?:website )?https?://(?:www\.)?([\w.-]+)", letter)
if "To Whom It May Concern" in letter and site:
return site.group(1).rstrip(".")
return record["recipient_company"]
for letter in DATA["website_letters"]:
record = extract(KIND, letter["document"], FIELDS)
opening = " ".join(letter["document"].split("To Whom It May Concern:")[1].split())
print(textwrap.fill(opening[:205] + " [...]", 100))
print(f" the model: {record['recipient_company']}")
print(f" with the rule: {addressee(letter['document'], record)}")
print(f" FDA lists it under: {letter['answer']['recipient_company']}")The Center for Tobacco Products of the U.S. Food and Drug Administration (FDA) recently reviewed the
website https://www.matesbrand.com and determined that nicotine pouch products listed there are
offered [...]
the model: Center for Tobacco Products
with the rule: matesbrand.com
FDA lists it under: matesbrand.com
The Center for Tobacco Products of the U.S. Food and Drug Administration (FDA) recently reviewed the
website https://www.vapetrinity.com and determined that a dissolvable tobacco product listed there
is of [...]
the model: Center for Tobacco Products
with the rule: vapetrinity.com
FDA lists it under: vapetrinity.comIn eight of the twelve it gave the office that wrote the letter, and in the other four a company the letter mentions further down. Changing the description did not help: with “Name of the company or website the letter is addressed to” the addressee was right in 9 of the 22 letters again.
These letters all open the same way, so a rule reads them better than a model does. addressee takes the website out of the first sentence when the letter is of that kind, and keeps the model’s answer when it is not.
Measure it#
Every letter the test set has an answer for on all four fields:
sample = DATA["sample"] # every letter the test set has an answer for on all four fields
right = {field["name"]: 0 for field in FIELDS}
with_rule = 0
for letter in sample:
record = extract(KIND, letter["document"], FIELDS)
for name in right:
right[name] += same(record[name], letter["answer"][name])
with_rule += same(addressee(letter["document"], record), letter["answer"]["recipient_company"])
for name, n in right.items():
print(f"{name:<34} {n} of {len(sample)}")
print(f"{'recipient_company, with the rule':<34} {with_rule} of {len(sample)}")recipient_company 9 of 22
issuing_office 21 of 22
letter_date 22 of 22
fei_number 21 of 22
recipient_company, with the rule 21 of 22Where a company is named, the model had it right in 9 letters of 10. The letter the rule does not fix names two companies, and the model picked the other one. The one miss on the office is a letterhead that says only “CBER”, which the model returned as written where FDA’s listing spells it out, and in the same letter it took the letter’s reference number for the establishment number.
We wrote the rule after reading the letters the model got wrong, and counted on the same 22 letters. Count again on letters of your own before you trust it.
On the whole test set#
All 125 letters of the test set, each asked for its own list of four to eight fields (the recipient’s name, address and state, FDA’s case number, and several fields the letters do not state):
| Field F1 | 78.4 |
|---|---|
Fields the letter does not state, left null | 194 of 197 |
| Values the model made up | 1 of 508 |
It almost never fills a field the letter does not have. What it gets wrong is which of several names or numbers in a long letter the field means.
Length costs accuracy. Over all 500 documents of the test set, field F1 was 85 for prompts under 1,000 tokens, 81 between 1,000 and 2,000, and 70 between 2,000 and 4,000. These letters are 1,050 to 1,750 tokens long. If your documents are much longer, cut them to the part that holds the facts before you send them: here, the first page.
Make it yours#
- Look at the misses, not only the score. Nine of 22 looked like a weak field. Reading the 13 misses showed one cause, and one rule took the field to 21.
- Use the model for what is written many ways and a rule for what is written one way. The two together are better than either.
- Check a field against another. An addressee that equals the issuing office is wrong on its face, and so is an establishment number that equals the letter’s own reference number. Both are one line of code.
- Set
max_tokens. The recipe uses 800, which is plenty for a record of four fields: these replies were about 40 tokens. A reply that reaches the limit is cut off, and the recipe raises instead of parsing half a record.
Run it#
pip install openai
curl -O https://contrastivelabs.com/cookbook/extract-warning-letters.py
curl --create-dirs -o data/extract-warning-letters.json \
https://contrastivelabs.com/cookbook/data/extract-warning-letters.json
python extract-warning-letters.pyThe file is this page’s code in one piece: extract-warning-letters.py. The letters are in data/extract-warning-letters.json, each with its link to FDA.