Extract · Reports
Turn an accident report into a database row
An investigator writes what happened in sentences: “On May 23, 2026, about 1500 eastern daylight time, a Cessna A188B, N8288G, was substantially damaged...”. A database wants columns. Nenya reads the report and returns one JSON object with the fields you list, the date already in YYYY-MM-DD and the regulation part as a number.
- The move
- Pull a fixed set of facts out of a narrative report, as JSON.
- The model’s role
- It takes the place of the person who keys the report into the system of record.
- Why it fits
- The facts are all in the first sentences, in a different order and wording each time. A pattern breaks on “an Enstrom F-28F helicopter” and “a Piper PA-24-260 airplane”. The model reads them as a person does.
- How it goes
- Report in → your field list in the system message, the report as the user message, a JSON schema on the reply → one record → check it, store it.
- Payoff
- Measured: 183 of 189 fields right on 27 real reports, and 24 of the 27 with every field right. On all 125 reports of our test set, each asked for its own list of fields, 87.2 field F1. About 630 tokens a report.
On this page
The data#
Preliminary reports of aviation accidents that the US National Transportation Safety Board (NTSB) published in 2026. They are public-domain records. Each comes with the values of the NTSB’s own database record of the case: those are the answers the extraction is checked against. They are a test set: the model has no training data for them.
The seven fields. Each has a name, a type and a description, and the description is where you say the format:
- event_date (string): Date of the accident, YYYY-MM-DD
- city (string): City or place nearest to the accident site
- state (string): US state of the accident site, as written in the report
- registration (string): Aircraft registration number
- aircraft_make (string): Aircraft manufacturer (make)
- aircraft_model (string): Aircraft model designation
- cfr_part (integer): Title 14 CFR part the flight was operated under, as a numberSet up#
pip install openai. The API is free and needs no key.
import json
import textwrap
from pathlib import Path
from openai import OpenAI
client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")The recipe#
This is the extract function of the API page, unchanged. The field list goes into the system message, the document is the user message and nothing else, and a JSON schema holds the reply to your keys and types. Every field may be null, so the model has a way to say “the text does not give this”.
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-accident-reports.json").read_text())
KIND = DATA["kind"] # "aviation accident report"
FIELDS = DATA["fields"] # what to pull out: a name, a type and a description for each field
for field in FIELDS:
print(f"- {field['name']} ({field['type']}): {field['description']}")The request#
report = DATA["examples"][0]
print(textwrap.fill(report["document"], 100))
record = extract(KIND, report["document"], FIELDS)
print()
print(json.dumps(record, indent=2))The response#
The report as the NTSB published it, then the record:
On May 23, 2026, about 1500 eastern daylight time, a Cessna A188B, N8288G, was substantially damaged
when it was involved in an accident near Doerun, Georgia. The pilot was not injured. The airplane
was operated as a Title 14 Code of Federal Regulations Part 137 agricultural flight. According to
the pilot, during his fourth flight of the day the airplane sustained a total loss of engine power
while en route to apply fertilizer to a corn field. The pilot initiated a forced landing to a field,
during which the airplane struck trees before it came to rest upright, resulting in substantial
damage to the fuselage and wings. The wreckage was retained for further examination.
{
"event_date": "2026-05-23",
"city": "Doerun",
"state": "Georgia",
"registration": "N8288G",
"aircraft_make": "Cessna",
"aircraft_model": "A188B",
"cfr_part": 137
}The report says “May 23, 2026” and “Part 137”. The record has 2026-05-23 and the number 137, because the descriptions ask for them that way.
Check it#
same compares a value with the answer: text by its letters and digits, numbers as numbers, and null only with null.
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, report["answer"][name]) else f"WRONG, the NTSB has {report['answer'][name]!r}"
print(f"{name:<15} {value!r:<14} {verdict}")event_date '2026-05-23' right
city 'Doerun' right
state 'Georgia' right
registration 'N8288G' right
aircraft_make 'Cessna' right
aircraft_model 'A188B' right
cfr_part 137 rightThree reports#
records = [extract(KIND, report["document"], FIELDS) for report in DATA["examples"]]
for record in records:
print(json.dumps(record)){"event_date": "2026-05-23", "city": "Doerun", "state": "Georgia", "registration": "N8288G", "aircraft_make": "Cessna", "aircraft_model": "A188B", "cfr_part": 137}
{"event_date": "2026-07-21", "city": "Malad City", "state": "Idaho", "registration": "N8624B", "aircraft_make": "Enstrom", "aircraft_model": "F-28F", "cfr_part": 91}
{"event_date": "2026-08-26", "city": "Seldovia", "state": "Alaska", "registration": "N9485P", "aircraft_make": "Piper", "aircraft_model": "PA-24-260", "cfr_part": 91}All three records are the NTSB’s, field for field.
One field for each fact#
The reports write the make and the model as one phrase: “a Cessna A188B”. If you want the model alone, ask for the make as well. Asked without a field for the make, the model puts both into the one field it has:
without_make = [field for field in FIELDS if field["name"] != "aircraft_make"]
for report, record in zip(DATA["examples"], records):
alone = extract(KIND, report["document"], without_make)
print(f"asked with aircraft_make: {record['aircraft_model']!r:<12} asked without it: {alone['aircraft_model']!r}")asked with aircraft_make: 'A188B' asked without it: 'Cessna A188B'
asked with aircraft_make: 'F-28F' asked without it: 'Enstrom F-28F'
asked with aircraft_make: 'PA-24-260' asked without it: 'Piper PA-24-260'Telling it what to leave out does not work. With the description changed to “Aircraft model designation, without the manufacturer’s name” and still no field for the make, the model field was right in 1 of the 27 reports. With a field for the make it is right in 24.
Measure it#
Every report the test set has an answer for on all seven fields:
sample = DATA["sample"] # every report the test set has an answer for on all seven fields
right = {field["name"]: 0 for field in FIELDS}
complete = 0
for report in sample:
record = extract(KIND, report["document"], FIELDS)
ok = {name: same(record[name], report["answer"][name]) for name in right}
complete += all(ok.values())
for name in right:
right[name] += ok[name]
print(f"{complete} of {len(sample)} reports with every field right")
for name, n in right.items():
print(f"{name:<15} {n} of {len(sample)}")24 of 27 reports with every field right
event_date 27 of 27
city 27 of 27
state 27 of 27
registration 27 of 27
aircraft_make 24 of 27
aircraft_model 24 of 27
cfr_part 27 of 27The three reports that are not complete each miss on the make and the model together, where the NTSB’s record splits the name in its own way: “Pipistrel D O O” and “Sinus 912”, “Vertical Aviation” and “Hummingbird”, “Montana” and “Coyote”.
On the whole test set#
All 125 reports of the test set, each asked for its own list of four to eight fields, some of which the report does not state:
| Field F1 | 87.2 |
|---|---|
Fields the report does not state, left null | 154 of 178 |
| Values the model made up | 2 of 785 |
So 24 fields came back filled although the report does not state them. Check what matters before you store it: the next cookbooks show two ways, rules that need no model (recall notices) and a look in the text (complaint details).
Make it yours#
- Describe every field. The description is the only place the model learns what a field means: the schema holds the shape of the reply and is never shown to the model. In our tests the same extraction scored 83 F1 with descriptions and 66 without.
- Say the format in the description:
YYYY-MM-DD, “as a number”, “as written in the report”. - Give each fact its own field when two facts stand together in the text.
- Let every field be
null. The recipe’s schema does. A field that has to be filled gets filled. - Keep
temperature: 0and readfinish_reason: the recipe raises when a reply was cut off.
Run it#
pip install openai
curl -O https://contrastivelabs.com/cookbook/extract-accident-reports.py
curl --create-dirs -o data/extract-accident-reports.json \
https://contrastivelabs.com/cookbook/data/extract-accident-reports.json
python extract-accident-reports.pyThe file is this page’s code in one piece: extract-accident-reports.py. The reports are in data/extract-accident-reports.json, each with its link to the NTSB. To start from the PDF the NTSB publishes, see PDFs and scans.