Cookbook

Extract · Notices

Pull the recalling firm and the quantity out of a recall notice

A recall notice packs a product, an address, lot codes, a reason and a quantity into a few lines with no fixed order: “Asteria Health 432 Industrial Ln, Birmingham, AL 35211” is somewhere in the middle of the product line. Nenya pulls the firm’s city, state and ZIP code and the quantity out of each notice, and leaves a field empty when the notice does not have it. This cookbook runs a batch in parallel and checks every record before it is stored.

The move
Turn semi-structured notices into rows: address parts, a quantity, and null where there is nothing.
The model’s role
It takes the place of a parser you would have to rewrite for every way a firm writes its address.
Why it fits
The notices are short (about 150 tokens) and there are many of them. Each is a request of well under half a second, and many can be in flight at once.
How it goes
Notices in → the same field list for each, eight requests at a time → one record each → rules that need no model → the rows that pass are stored.
Payoff
Measured: 85 of 85 fields right on 17 real notices, and no value in the field the notices do not state. On all 125 notices of our test set, each asked for its own list of fields, 81.9 field F1. Seventeen notices took about a second.

The data#

Recalls of food, drugs and medical devices that the US Food and Drug Administration (FDA) published in 2026, from openFDA (public domain). Each notice comes with the values of FDA’s own record of the recall: those are the answers. They are a test set: the model has no training data for them.

Five fields. The last one, the recall’s classification, is in FDA’s record and not in the text of the notice, so the right answer for it is always null:

Output
- firm_city (string): City of the recalling firm
- firm_state (string): US state of the recalling firm, as written in the report
- firm_zip_code (string): Five-digit ZIP code of the recalling firm
- quantity (integer): Number of units recalled, as a number without the unit
- fda_classification (string): FDA recall classification: Class I, Class II or Class III

Set up#

pip install openai. The API is free and needs no key.

Python
import json
import re
import time
from concurrent.futures import ThreadPoolExecutor
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.

Python
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)
Python
DATA = json.loads((Path(__file__).parent / "data" / "extract-recall-notices.json").read_text())
KIND = DATA["kind"]                         # "product recall report"
FIELDS = DATA["fields"]

for field in FIELDS:
    print(f"- {field['name']} ({field['type']}): {field['description']}")

The request#

Python
notice = DATA["examples"][0]
print(notice["document"])

record = extract(KIND, notice["document"], FIELDS)
print()
print(json.dumps(record, indent=2))

The body the function sends for this notice. The field list is in the system message, and the schema is in response_format:

Request body
{
  "model": "nenya",
  "messages": [
    {
      "role": "system",
      "content": "You extract structured data from product recall reports. For each document the user sends, give these fields.\n\nFields:\n- firm_city (string): City of the recalling firm\n- firm_state (string): US state of the recalling firm, as written in the report\n- firm_zip_code (string): Five-digit ZIP code of the recalling firm\n- quantity (integer): Number of units recalled, as a number without the unit\n- fda_classification (string): FDA recall classification: Class I, Class II or Class III\n\nAnswer with one JSON object with exactly these keys. Use null for a field the text does not give."
    },
    {
      "role": "user",
      "content": "Product: ESTRADIOL, 37.5 mg, 1 Sterile Pellet, Asteria Health 432 Industrial Ln, Birmingham, AL 35211, NDC: 79559-3037-32.\nCode information: Lot#: 253000125, Exp. 06/09/2026.\nReason for recall: Presence of Foreign substance - potential presence of metal particulate matter\nQuantity: 715 pellets\nDistribution: Nationwide in the USA"
    }
  ],
  "temperature": 0,
  "max_tokens": 800,
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "record",
      "schema": {
        "type": "object",
        "properties": {
          "firm_city": {
            "type": [
              "string",
              "null"
            ]
          },
          "firm_state": {
            "type": [
              "string",
              "null"
            ]
          },
          "firm_zip_code": {
            "type": [
              "string",
              "null"
            ]
          },
          "quantity": {
            "type": [
              "integer",
              "null"
            ]
          },
          "fda_classification": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "required": [
          "firm_city",
          "firm_state",
          "firm_zip_code",
          "quantity",
          "fda_classification"
        ],
        "additionalProperties": false
      }
    }
  }
}

The response#

Output
Product: ESTRADIOL, 37.5 mg, 1 Sterile Pellet, Asteria Health 432 Industrial Ln, Birmingham, AL 35211, NDC: 79559-3037-32.
Code information: Lot#: 253000125, Exp. 06/09/2026.
Reason for recall: Presence of Foreign substance - potential presence of metal particulate matter
Quantity: 715 pellets
Distribution: Nationwide in the USA

{
  "firm_city": "Birmingham",
  "firm_state": "AL",
  "firm_zip_code": "35211",
  "quantity": 715,
  "fda_classification": null
}

“715 pellets” became the number 715, and the classification is null: the notice does not say.

The reply
{
  "model": "nenya-1",
  "choices": [
    {
      "message": {
        "content": "{\"firm_city\": \"Birmingham\", \"firm_state\": \"AL\", \"firm_zip_code\": \"35211\", \"quantity\": 715, \"fda_classification\": null}",
        "role": "assistant"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "completion_tokens": 38,
    "prompt_tokens": 271,
    "total_tokens": 309
  }
}

Check it#

Python
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, notice["answer"][name]) else f"WRONG, FDA has {notice['answer'][name]!r}"
    print(f"{name:<19} {value!r:<13} {verdict}")
Output
firm_city           'Birmingham'  right
firm_state          'AL'          right
firm_zip_code       '35211'       right
quantity            715           right
fda_classification  None          right

Every notice, eight at a time#

Python
notices = DATA["sample"]                    # every notice the test set has an answer for on all five fields
start = time.perf_counter()
with ThreadPoolExecutor(8) as pool:
    records = list(pool.map(lambda notice: extract(KIND, notice["document"], FIELDS), notices))
seconds = time.perf_counter() - start

for notice, record in zip(notices, records):
    ok = all(same(record[name], notice["answer"][name]) for name in record)
    where = f"{record['firm_city']}, {record['firm_state']} {record['firm_zip_code']}"
    print(f"{notice['id'][8:]:<12} {where:<28} {record['quantity']:>9,}  {record['fda_classification']}  "
          f"{'right' if ok else 'WRONG: ' + json.dumps(notice['answer'])}")
print(f"{len(notices)} notices in {seconds:.1f} s")
Output
D-0315-2026  Birmingham, AL 35211               715  None  right
H-1096-2026  Raleigh, NC 27606               41,159  None  right
H-0802-2026  Chandler, AZ 85225                 127  None  right
H-0642-2026  Brooklyn, NY 11237                 595  None  right
H-1262-2026  Ravenna, OH 44266                  249  None  right
D-0542-2026  Warren, NJ 07059               285,330  None  right
D-0751-2026  Columbia, MO 65202              24,608  None  right
H-1277-2026  Santa Rosa, CA 95404             3,486  None  right
D-0160-2027  Dallas, TX 75227                12,028  None  right
H-0536-2026  Portage, WI 53901              263,440  None  right
H-1104-2026  Raleigh, NC 27606                9,932  None  right
H-0804-2026  Chandler, AZ 85225                  25  None  right
D-0795-2026  SHIRLEY, NY 11967               89,775  None  right
D-0306-2026  East Brunswick, NJ 08816        60,000  None  right
H-0535-2026  Portage, WI 53901                7,840  None  right
H-0611-2026  Omaha, Nebraska 68107              370  None  right
H-1237-2026  Beloit, WI 53511                 6,970  None  right
17 notices in 1.1 s

Each row ends with the comparison with FDA’s record.

Validate before you store#

A record that is the right shape can still hold something your table does not want. Rules that need no model catch that:

Python
def problems(record):
    """What is wrong with a record by rules that need no model. An empty list: store it."""
    found = []
    if not re.fullmatch(r"\d{5}", record["firm_zip_code"] or ""):
        found.append("the ZIP code is not five digits")
    if not re.fullmatch(r"[A-Z]{2}", record["firm_state"] or ""):
        found.append("the state is not a two-letter code")
    if not isinstance(record["quantity"], int) or record["quantity"] <= 0:
        found.append("the quantity is not a positive whole number")
    if record["fda_classification"] not in (None, "Class I", "Class II", "Class III"):
        found.append("the classification is not one FDA uses")
    return found


stored = [record for record in records if not problems(record)]
print(f"{len(stored)} of {len(records)} records pass every rule")
Output
16 of 17 records pass every rule

The record that does not pass is the notice from Omaha: it writes the state out, “Nebraska”, and the field asks for the state “as written”. The model did what it was asked. The rule is what tells you that this row needs NE before it goes into a two-letter column. Map it in code, or change the description to ask for the two-letter code and measure again.

Measure it#

Python
right = {field["name"]: 0 for field in FIELDS}
complete = 0
for notice, record in zip(notices, records):
    ok = {name: same(record[name], notice["answer"][name]) for name in right}
    complete += all(ok.values())
    for name in right:
        right[name] += ok[name]

print(f"{complete} of {len(notices)} notices with every field right")
for name, n in right.items():
    print(f"{name:<19} {n} of {len(notices)}")
Output
17 of 17 notices with every field right
firm_city           17 of 17
firm_state          17 of 17
firm_zip_code       17 of 17
quantity            17 of 17
fda_classification  17 of 17

On the whole test set#

All 125 notices of the test set, each asked for its own list of four to eight fields (brand names, the recalling firm’s name and street address among them):

Field F181.9
Fields the notice does not state, left null175 of 180
Values the model made up4 of 497

The cookbook’s five fields came out 85 of 85. The whole-set figure covers more kinds of field, names among them, where a notice can hold a manufacturer, a distributor and a brand and the model has to pick the one your field means.

Make it yours#

  • Run in parallel. There are no rate limits.
  • Put the format you want in the description (“two-letter state code”, “five digits”), then keep the rule all the same. The description asks. The rule checks.
  • Ask for numbers as numbers. quantity (integer): Number of units recalled, as a number without the unit turns “41,159 bars” into 41159.
  • Expect null. On the whole test set 175 of the 180 fields a notice does not state came back null. Do not make a field required unless every document has it: a field that has to be filled gets filled.

Run it#

Terminal
pip install openai
curl -O https://contrastivelabs.com/cookbook/extract-recall-notices.py
curl --create-dirs -o data/extract-recall-notices.json \
     https://contrastivelabs.com/cookbook/data/extract-recall-notices.json
python extract-recall-notices.py

The file is this page’s code in one piece: extract-recall-notices.py. The notices are in data/extract-recall-notices.json, each with its openFDA link.

Loading…

Need fine-tuning, on-prem deployment, your own evals or support?

Nenya 1 is free to call here and free to download. Book a call for a fine-tuned model or an on-prem deployment.