Cookbook

Classify · Customer complaints

Route a vehicle safety complaint to the right engineering team

A complaint arrives as a paragraph of the customer’s own words: what happened, at what speed, what the dealer said. Before anyone can act on it, it has to reach the team that owns the part. Nenya reads the paragraph, names the component, and gives a confidence with it, so you route what it is sure of and put the rest in front of a person.

The move
Sort free-text complaints into your own list of components.
The model’s role
It takes the place of the first read by a person.
Why it fits
The text is long, messy and written by the public. A keyword rule misses “the car would not go” and a large model is slow and costly at inbox volume.
How it goes
Complaint in → the question, the complaint and your labels in one message → one label and a confidence → route, or queue for review.
Payoff
Measured: on 250 real complaints the label matched the one the filer chose in 74.8%. Where the model was at least 95% sure, which was half of the complaints, it matched in 91.1%. About 410 tokens and a sixth of a second a complaint.

The data#

250 complaints that drivers filed with the US road-safety regulator (NHTSA) between January and November 2026, each with the component its filer ticked on the complaint form. They are public-domain records, and they are a test set: the model has no training data for this task.

The label is the filer’s choice, not an engineer’s. Keep that in mind when you read the numbers: a driver whose car stalls may tick “Fuel/propulsion system” where an engineer would say “Engine”.

There are twelve components. The names are NHTSA’s, and each has a few words after it that say what it covers:

Output
Which vehicle component is this safety complaint about?
- Air bags: air bags, their sensors and the air bag (SRS) warning light
- Back over prevention: rear-view (backup) camera, its display and rear sensors
- Electrical system: battery, wiring, ignition, instrument panel, software and control modules
- Engine: the engine and its cooling: stalling, overheating, oil consumption, engine failure
- Exterior lighting: headlights, tail lights, brake lights and turn signals
- Forward collision avoidance: automatic emergency braking, forward collision warning, adaptive cruise control
- Fuel/propulsion system: fuel pump, fuel tank, fuel lines, injection and leaks; on an electric vehicle the drive battery and motor
- Power train: transmission, clutch, driveshaft, axles and differential
- Service brakes: brake pedal, pads, rotors, brake fluid and lines, anti-lock brakes
- Steering: steering wheel, column, rack and power steering
- Structure: body, frame, doors, hood, liftgate, paint, rust and water leaks
- Visibility/wiper: windshield and windows, wipers and washers, defroster, mirrors, sunroof

Set up#

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

Python
import json
import math
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 classify function of the API page, unchanged. It sends one user message in the layout the model was trained on (the question, the text under a heading, Options:, then Answer with the label only.), holds the reply to your labels, and turns the reply’s token probabilities into a confidence.

Python
def classify(question, text, labels, heading="Text", descriptions=None, allow_none=False):
    """(label, confidence)"""
    options = "\n".join(f"- {label}: {descriptions[label]}" if descriptions else f"- {label}" for label in labels)
    prompt = f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\nAnswer with the label only."
    if allow_none:
        prompt += ' If none of the options fits, answer "none".'
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "user", "content": prompt}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=24,
        logprobs=True,                      # for the confidence
        extra_body={"structured_outputs": {"choice": labels + (["none"] if allow_none else [])}},
    )
    choice = reply.choices[0]
    tokens = [t for t in choice.logprobs.content if not t.token.startswith("<|")]
    confidence = math.exp(sum(t.logprob for t in tokens))
    return choice.message.content, confidence
Python
DATA = json.loads((Path(__file__).parent / "data" / "classify-safety-complaints.json").read_text())
QUESTION = DATA["question"]
COMPONENTS = DATA["labels"]                 # the twelve components a complaint can be about
ABOUT = DATA["descriptions"]                # a few words on what each one covers

print(QUESTION)
for name in COMPONENTS:
    print(f"- {name}: {ABOUT[name]}")

The request#

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

label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
print()
print(f"model: {label} ({confidence:.0%} sure)")
print(f"filer: {complaint['label']}")

The body the function sends for this complaint:

Request body
{
  "model": "nenya",
  "messages": [
    {
      "role": "user",
      "content": "Which vehicle component is this safety complaint about?\n\nComplaint:\nTurned rear defroster on before getting on the highway as temps were in the upper 30s. About 5 minutes down the highway there was a loud pop sound and the rear windshield began splintering. By the time we got to a safe place to stop the entire shield was shattered and there were several holes. Purchased trash bags and tape to cover the windshield and during the process most of the glass had fallen a part. We had a 3 hour drive home without being able to see out the rear.\n\nOptions:\n- Air bags: air bags, their sensors and the air bag (SRS) warning light\n- Back over prevention: rear-view (backup) camera, its display and rear sensors\n- Electrical system: battery, wiring, ignition, instrument panel, software and control modules\n- Engine: the engine and its cooling: stalling, overheating, oil consumption, engine failure\n- Exterior lighting: headlights, tail lights, brake lights and turn signals\n- Forward collision avoidance: automatic emergency braking, forward collision warning, adaptive cruise control\n- Fuel/propulsion system: fuel pump, fuel tank, fuel lines, injection and leaks; on an electric vehicle the drive battery and motor\n- Power train: transmission, clutch, driveshaft, axles and differential\n- Service brakes: brake pedal, pads, rotors, brake fluid and lines, anti-lock brakes\n- Steering: steering wheel, column, rack and power steering\n- Structure: body, frame, doors, hood, liftgate, paint, rust and water leaks\n- Visibility/wiper: windshield and windows, wipers and washers, defroster, mirrors, sunroof\n\nAnswer with the label only."
    }
  ],
  "temperature": 0,
  "max_tokens": 24,
  "logprobs": true,
  "structured_outputs": {
    "choice": [
      "Air bags",
      "Back over prevention",
      "Electrical system",
      "Engine",
      "Exterior lighting",
      "Forward collision avoidance",
      "Fuel/propulsion system",
      "Power train",
      "Service brakes",
      "Steering",
      "Structure",
      "Visibility/wiper"
    ]
  }
}

The response#

What the code printed. The complaint is the customer’s text as filed, and the last line is the component the filer chose:

Output
Turned rear defroster on before getting on the highway as temps were in the upper 30s. About 5
minutes down the highway there was a loud pop sound and the rear windshield began splintering. By
the time we got to a safe place to stop the entire shield was shattered and there were several
holes. Purchased trash bags and tape to cover the windshield and during the process most of the
glass had fallen a part. We had a 3 hour drive home without being able to see out the rear.

model: Visibility/wiper (99% sure)
filer: Visibility/wiper

And the reply itself. The confidence is the product of the probabilities of the reply’s tokens: exp(-0.0102 + 0 + 0) is 0.99.

The reply
{
  "model": "nenya-1",
  "choices": [
    {
      "message": {
        "content": "Visibility/wiper",
        "role": "assistant"
      },
      "finish_reason": "stop",
      "logprobs": {
        "content": [
          {
            "token": "Visibility",
            "logprob": -0.0102
          },
          {
            "token": "/w",
            "logprob": -0.0
          },
          {
            "token": "iper",
            "logprob": -0.0
          }
        ]
      }
    }
  ],
  "usage": {
    "completion_tokens": 4,
    "prompt_tokens": 408,
    "total_tokens": 412
  }
}

Six complaints#

Python
for complaint in DATA["examples"]:
    label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
    vehicle = f"{complaint['model_year']} {complaint['make']} {complaint['model']}"
    print(f"{label:<24} {confidence:4.0%}   {vehicle:<28} {complaint['text'][:44]}...")
Output
Visibility/wiper          99%   2021 KIA SELTOS              Turned rear defroster on before getting on t...
Engine                   100%   2021 JEEP WRANGLER           At 47000 miles the oil cooler cracked, altho...
Structure                 93%   2018 TOYOTA TUNDRA           Front Upper Grille Hood Scoop becomes loose ...
Electrical system         96%   2026 SUBARU UNCHARTED        It is an EV, the 12 volt battery went dead a...
Fuel/propulsion system    94%   2018 RAM 1500                MULTIPLE REPORTS ACROSS MANY YEARS OF DEFECT...
Back over prevention      98%   2016 FORD ESCAPE             The contact owns a 2016 Ford Escape. The con...

All six are the component the filer chose.

The unsure ones go to a person#

The model is not always right, and it knows when it is guessing. Pick a threshold, act on what is over it, and queue the rest. Here are two complaints the model is unsure of, then two it is sure of:

Python
THRESHOLD = 0.9
for complaint in DATA["review"] + DATA["examples"][:2]:
    label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
    action = f"route to {label}" if confidence >= THRESHOLD else f"a person looks (the model leans to {label})"
    print(f"{confidence:4.0%}   {action:<52} filer: {complaint['label']}")
Output
 66%   a person looks (the model leans to Electrical system) filer: Electrical system
 49%   a person looks (the model leans to Engine)           filer: Power train
 99%   route to Visibility/wiper                            filer: Visibility/wiper
100%   route to Engine                                      filer: Engine

The first is a real failure of an electric car’s charging unit, in the driver’s shorthand (“ICCU Failure”, “turtle mode”): the model leans the right way and is not sure. In the second the model leans to the engine where the filer chose the power train (“hesitates for 1-2 seconds when accelerating from a stop”). Neither is routed by the model. Both land with a person, with the model’s guess attached.

Measure it#

Before you rely on it, run it on examples you know the answer to. This runs the recipe on 60 complaints taken from the test set without looking at the answers:

Python
sample = DATA["sample"]                     # 60 complaints, taken without looking at the answers
agree = sure = sure_agree = 0
for complaint in sample:
    label, confidence = classify(QUESTION, complaint["text"], COMPONENTS, heading="Complaint", descriptions=ABOUT)
    agree += label == complaint["label"]
    if confidence >= THRESHOLD:
        sure += 1
        sure_agree += label == complaint["label"]

print(f"{agree} of {len(sample)} agree with the filer ({agree / len(sample):.0%})")
print(f"the model is at least {THRESHOLD:.0%} sure of {sure}; {sure_agree} of those agree ({sure_agree / sure:.0%})")
print(f"so {len(sample) - sure} of {len(sample)} would go to a person")
Output
44 of 60 agree with the filer (73%)
the model is at least 90% sure of 32; 28 of those agree (88%)
so 28 of 60 would go to a person

On the whole test set#

All 250 complaints, asked exactly as above, one request at a time:

Matched the filer’s component
Label names only68.4% (171 of 250)
Names with a few words on what each covers (this recipe)74.8% (187 of 250)

Describing the labels is worth six points here, because NHTSA’s names are jargon: with the descriptions “Back over prevention” went from 14 to 19 right out of 20, and “Structure” from 11 to 16.

The confidence tells you which answers to trust:

Act only when the confidence is at leastComplaints you keepMatched among them
0.7082.8%80.2%
0.8074.4%82.8%
0.9058.4%87.0%
0.9549.2%91.1%

Two components stay hard whatever you do. “Fuel/propulsion system” matched in 4 of 20, and 16 of those 20 came back as “Engine”: drivers file a stalling car under either. “Forward collision avoidance” matched in 6 of 20. The ten others are between 14 and 19 of 20, and “Engine” 27 of 29. If two of your labels overlap like the first pair, merge them, or let a person split them.

Make it yours#

  • Use your own list. Swap the twelve components for your teams or queues. Keep it to 20 labels or fewer: on this task, with every one of NHTSA’s 31 components on offer, accuracy fell to 62%.
  • Say what each label covers when its name is not plain to an outsider. A few words are enough.
  • Keep the wording. The question, the heading, Options: and Answer with the label only. are the layout the model was trained on. The same task asked as “Classify the following...” gave a clean label 6% of the time.
  • Do not use a tool call or a system message for this. Both scored lower in our tests (70% and 61% against 81%).
  • Pick the threshold from the mistakes you can afford. At 0.9 you route 58% of the complaints by machine and 87% of those are right. What falls under it goes to a person or to a larger model.

Run it#

Terminal
pip install openai
curl -O https://contrastivelabs.com/cookbook/classify-safety-complaints.py
curl --create-dirs -o data/classify-safety-complaints.json \
     https://contrastivelabs.com/cookbook/data/classify-safety-complaints.json
python classify-safety-complaints.py

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

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.