Cookbook

Extract · Customer complaints

Pull the vehicle and the mileage out of a consumer complaint

“The contact owns a 2024 Jeep Wrangler 4XE... The failure mileage was 14,317.” Somewhere in every complaint are the facts a case needs: which vehicle, which year, how many miles. Customers do not fill in forms the way a database likes, so the facts have to be read out of the text. Nenya returns them as a record, and leaves a field empty when the customer did not say. The cookbook ends with a check that costs nothing: is every value the model returned in the text?

The move
Read the vehicle and the numbers out of free text, and tell a value that was said from one that was not.
The model’s role
It fills in the form the customer did not.
Why it fits
The text is short (about 150 tokens) and messy, and the same fact is written many ways: “14,317”, “110,000 miles”, “a 2018 Ram 2500”. A missing fact has to stay missing: a made-up repair cost is worse than none.
How it goes
Complaint in → field list, complaint, schema → one record → every value looked up in the text → store, or flag.
Payoff
Measured: 128 of 130 fields right on 26 real complaints, and the field the complaints do not state left null in all 26. On all 125 complaints of our test set, each asked for its own list of fields, 84.1 field F1. About 300 tokens a complaint.

The data#

Complaints that drivers filed with the US road-safety regulator (NHTSA) in 2026. They are public-domain records. Beside the text, each filer filled in a form with the vehicle and the mileage: those values are the answers. They are a test set: the model has no training data for them.

Five fields. The last, the cost of the repair, is one these complaints do not state, so the right answer for it is null:

Output
- make (string): Vehicle make (brand)
- model (string): Vehicle model name, without the make
- model_year (integer): Vehicle model year
- mileage (integer): Odometer reading in miles when the problem happened
- repair_cost_usd (number): Cost of the repair in US dollars

Set up#

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

Python
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#

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-complaint-details.json").read_text())
KIND = DATA["kind"]                         # "vehicle safety complaint"
FIELDS = DATA["fields"]

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

The request#

Python
complaint = DATA["examples"][0]
print(textwrap.fill(complaint["document"], 100))

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

The response#

Output
The contact owns a 2024 Jeep Wrangler 4XE. The contact received notification of NHTSA Campaign
Number: 25V766000 (Engine); however, the part to do the recall repair was unavailable. The contact
stated that the manufacturer had exceeded a reasonable amount of time for the recall repair. The
contact stated that while driving at highway speeds, the vehicle was unstable. The were an
abnormally loud sound coming from the engine while driving. The failure was more noticeable while
driving in EV Mode. The contact stated that the vehicle had been removed from the Manufacturer's
website for sale and that there were lawsuits involving the vehicle. The dealer was contacted and
confirmed that there was no fix available. The manufacturer was made aware of the issue and opened a
case. The manufacturer referred the contact to the NHTSA Hotline to report the failure. The failure
mileage was 14,317.

{
  "make": "Jeep",
  "model": "Wrangler 4XE",
  "model_year": 2024,
  "mileage": 14317,
  "repair_cost_usd": null
}

“14,317” is the integer 14317, the model name is without the make, and nothing in the complaint is a repair cost, so that field is null. The complaint mentions a recall campaign number, 25V766000, with digits in it. The model did not mistake it for the mileage.

The reply
{
  "model": "nenya-1",
  "choices": [
    {
      "message": {
        "content": "{\"make\": \"Jeep\", \"model\": \"Wrangler 4XE\", \"model_year\": 2024, \"mileage\": 14317, \"repair_cost_usd\": null}",
        "role": "assistant"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "completion_tokens": 42,
    "prompt_tokens": 336,
    "total_tokens": 378
  }
}

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, complaint["answer"][name]) else f"WRONG, the form has {complaint['answer'][name]!r}"
    print(f"{name:<16} {value!r:<15} {verdict}")
Output
make             'Jeep'          right
model            'Wrangler 4XE'  right
model_year       2024            right
mileage          14317           right
repair_cost_usd  None            right

Three complaints#

Python
for complaint in DATA["examples"]:
    record = extract(KIND, complaint["document"], FIELDS)
    print(json.dumps(record))
Output
{"make": "Jeep", "model": "Wrangler 4XE", "model_year": 2024, "mileage": 14317, "repair_cost_usd": null}
{"make": "Ram", "model": "2500", "model_year": 2018, "mileage": 150000, "repair_cost_usd": null}
{"make": "Jeep", "model": "Cherokee", "model_year": 2018, "mileage": 110000, "repair_cost_usd": null}

All three records are the forms’, field for field.

Is every value in the text?#

A model can return a value that is nowhere in the document. It is rare here (see below), and it is the mistake you least want in a database. For an extraction that copies values out of a text there is a check that needs no second model: look each value up in the text.

Python
def not_in_text(record, text):
    """The fields whose value cannot be found in the text. A number is looked for with and without the comma."""
    missing = []
    for name, value in record.items():
        if value is None:
            continue
        spellings = {str(value), f"{value:,}"} if isinstance(value, int) else {str(value)}
        if not any(spelling.lower() in text.lower() for spelling in spellings):
            missing.append(name)
    return missing


sample = DATA["sample"]                     # every complaint the test set has an answer for on all five fields
records = [extract(KIND, complaint["document"], FIELDS) for complaint in sample]
flagged = [(complaint, record) for complaint, record in zip(sample, records)
           if not_in_text(record, complaint["document"])]
print(f"{len(sample) - len(flagged)} of {len(sample)} records have every value in the text")
for complaint, record in flagged:
    print(f"   {complaint['id']}: {not_in_text(record, complaint['document'])} is not in the text as written")
Output
26 of 26 records have every value in the text

A record that fails goes to a person, or the failed field is set to null. The check works for values that are copied. It does not work for values the model is asked to rewrite, such as a date turned into YYYY-MM-DD: compare those after parsing.

Measure it#

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

print(f"{complete} of {len(sample)} complaints with every field right")
for name, n in right.items():
    print(f"{name:<16} {n} of {len(sample)}")
Output
24 of 26 complaints with every field right
make             26 of 26
model            24 of 26
model_year       26 of 26
mileage          26 of 26
repair_cost_usd  26 of 26

The two misses are both the model name with a number after it kept on: “XMAX 300” where the form has “XMAX”, “Promaster 3500” where it has “Promaster”. Both are in the text, so the check above does not flag them: it finds values that were made up, not values that say a little more than you wanted.

On the whole test set#

All 125 complaints of the test set, each asked for its own list of four to eight fields (speed, dates and the state among them, and several fields the complaints do not state):

Field F184.1
Fields the complaint does not state, left null184 of 189
Values the model made up7 of 519

Seven made-up values in 519 is where the text check earns its place.

Make it yours#

  • Add a field the documents do not have when you test, as repair_cost_usd is here. It is the only way to see whether the model fills gaps.
  • Say what a number counts in the description: “Odometer reading in miles when the problem happened” picked 14,317 and left the recall number alone.
  • Say “without the make” if you want it so, and give the make a field of its own (accident reports shows what happens otherwise).
  • Look values up in the text before you store them, and compare rewritten values (dates, amounts) after parsing.

Run it#

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

The file is this page’s code in one piece: extract-complaint-details.py. The complaints are in data/extract-complaint-details.json, each with its link to NHTSA.

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.