Call tools · Safety complaints and recall records
Answer a customer from your own records
A customer writes a paragraph about a camera that went black, and somewhere in the middle there is a recall number. The answer to “is that recall real, and what do I do?” is in your records, not in the model. The model’s work is to find the vehicle and the number in the message, to call your look-up with them, and to word an answer from the one record that comes back.
- The move
- Message in → one call to your look-up → an answer worded from the record.
- The model’s role
- It reads the message and fills in the call, and it words the answer. Your code finds the record.
- Why it fits
- The facts are in your records and have to be exact. A look-up by number is exact when code does it, and a small model is good at pulling a make, a model, a year and a number out of a paragraph.
- How it goes
- Complaint in → the model calls
find_recallswith the vehicle and the campaign numbers → your function returns those records, or a sentence that says there are none → the model answers. - Payoff
- Measured: on 29 real complaints, 28 look-ups were exactly right and 28 answers said what the records say. With a tool that returned the vehicle’s whole list of recalls and left the finding to the model, 22 of 29.
On this page
The data#
29 complaints filed with the US road-safety regulator (NHTSA) in 2026: every complaint of our test set that names a recall campaign and states its vehicle. The vehicle on the complaint’s form (make, model, year) is the test set’s answer. They are public records, in the public domain.
The records the tool reads are real too: NHTSA’s recall records for those vehicles, 218 of them, as its public service returned them on 2 December 2026. Whether a campaign is on record for a vehicle is read from there. 28 of the 29 complaints name a campaign that is on record for their vehicle, and one names a campaign that is not.
Set up#
pip install openai. The API is free and needs no key.
import contextlib
import io
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 loop#
The run_tools function of the API page, unchanged, with its two helpers. It sends the conversation, runs the calls the model asks for, sends the results back, and stops when the model answers in words. A function raises Final when there is nothing more to try.
class Final(Exception):
"""A function raises this when there is nothing more to try. Its message goes to the model as the result,
and no tools are offered after it, so the model answers in words."""
def run_tools(messages, tools, functions, tool_choice="auto", max_turns=6):
"""Run the conversation until the model answers in words. functions: {tool name: Python function}."""
messages = list(messages)
for _ in range(max_turns):
offer = {"tools": tools, "tool_choice": tool_choice} if tools else {"temperature": 0}
reply = client.chat.completions.create(model="nenya", messages=messages, **offer)
message = reply.choices[0].message
if not message.tool_calls:
return message.content
messages.append(message.model_dump(exclude_none=True)) # the model's message, as it came
for call in message.tool_calls:
arguments = json.loads(call.function.arguments) # a JSON string: parse it, then check it
print(f"-> {call.function.name}({arguments})")
try:
result = json.dumps(functions[call.function.name](**arguments))
except Final as final: # nothing more to try: a sentence for the model, and no more tools
result, tools = str(final), None
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
tool_choice = "auto" # a forced first step must not force every later one
raise RuntimeError("the model kept calling tools: stop and look")
def tool(name, description, properties, required):
return {"type": "function", "function": {"name": name, "description": description, "parameters": {
"type": "object", "properties": properties, "required": required}}}The records#
Two small functions that are your side of the work. One finds campaign numbers by their shape. The other finds a vehicle’s records, and forgives a longer name than the records use.
DATA = json.loads((Path(__file__).parent / "data" / "tools-recall-lookup.json").read_text())
RECALLS = DATA["recalls"] # NHTSA's recall records, by "year make model"
def campaign_numbers(text):
"""The NHTSA campaign numbers in a text: two digits, V or E, six digits."""
return sorted(set(re.findall(r"\b\d{2}[VE]\d{6}\b", str(text).upper())))
def recalls_for(make, model, model_year):
"""The records of a vehicle. People write "Promaster 3500" where the records say "Promaster", so words are
dropped from the end of the model's name until something matches."""
words = str(model).split()
while words:
records = RECALLS.get(f"{model_year} {make} {' '.join(words)}".lower())
if records:
return records
words = words[:-1]
return []The tool#
One tool. It takes the vehicle and the campaign numbers the customer mentions, and it returns those records and nothing else. When there is nothing to return it raises Final with a sentence the model can pass on.
SYSTEM = """You are the assistant of a vehicle recall desk. You answer from NHTSA's recall records.
Rules:
- Always look the recall up first.
- Answer from what the tool returns: say whether the recall is on record for the vehicle, and what the remedy is.
- Keep answers short and plain."""
VEHICLE = {"make": {"type": "string", "description": "The vehicle's make (brand)"},
"model": {"type": "string", "description": "The vehicle's model, without the make"},
"model_year": {"type": "integer", "description": "The model year"}}
TOOLS = [tool("find_recalls", "Look recall campaigns up in NHTSA's records for a vehicle.",
dict(VEHICLE, campaigns={"type": "array", "items": {"type": "string"},
"description": "Every NHTSA campaign number the customer mentions, "
"such as 24V123000"}),
["make", "model", "model_year", "campaigns"])]
looked_up = [] # every call the model makes, to check afterwards
def find_recalls(make, model, model_year, campaigns):
"""Your own code: an exact look-up. Here it reads a file. In production it asks your database, or NHTSA's
service. It returns the records asked for and nothing else."""
wanted = campaign_numbers(campaigns) # keep what has the shape of a campaign number, whatever else came
looked_up.append({"make": make, "model": model, "model_year": model_year, "campaigns": wanted})
found = [{"campaign": r["NHTSACampaignNumber"], "component": r["Component"].split(":")[0].capitalize(),
"remedy": r["Remedy"]}
for r in recalls_for(make, model, model_year) if r["NHTSACampaignNumber"] in wanted]
if not found: # nothing to report: a sentence for the model, and no more tools
raise Final(f"NHTSA has no recall {' or '.join(wanted) or 'with that number'} on record for a {model_year} "
f"{make} {model}. Tell the user so, and ask them to check the campaign number and the vehicle.")
return {"on_record": found,
"not_on_record_for_this_vehicle": [c for c in wanted if c not in [f["campaign"] for f in found]]}
QUESTION = "Is the recall they mention on NHTSA's record for their vehicle's model and year, and what is the remedy?"
def ask(complaint):
"""The model's answer to one customer's complaint, with the look-up done on the way."""
return run_tools([{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"A customer writes:\n\n{complaint}\n\n{QUESTION}"}],
TOOLS, {"find_recalls": find_recalls})The request#
customer = DATA["examples"][0]
print(textwrap.fill(customer["document"], 100))
print()
answer = ask(customer["document"])
print(textwrap.fill(answer, 100))The first request the loop sends. The model sees the system message, the complaint and the tool:
{
"model": "nenya",
"messages": [
{
"role": "system",
"content": "You are the assistant of a vehicle recall desk. You answer from NHTSA's recall records.\n\nRules:\n- Always look the recall up first.\n- Answer from what the tool returns: say whether the recall is on record for the vehicle, and what the remedy is.\n- Keep answers short and plain."
},
{
"role": "user",
"content": "A customer writes:\n\nThe contact owns a 2016 Ford Escape. The contact stated that while attempting to reverse, the rear-view camera displayed a blank image, nearly causing the vehicle to crash with another vehicle. The contact received notification of NHTSA Campaign Number: 25V695000 (Back Over Prevention); however, the part to do the recall repair was not yet available. The contact stated that the manufacturer had exceeded a reasonable amount of time for the recall repair. The approximate failure mileage was 171,237.\n\nIs the recall they mention on NHTSA's record for their vehicle's model and year, and what is the remedy?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "find_recalls",
"description": "Look recall campaigns up in NHTSA's records for a vehicle.",
"parameters": {
"type": "object",
"properties": {
"make": {
"type": "string",
"description": "The vehicle's make (brand)"
},
"model": {
"type": "string",
"description": "The vehicle's model, without the make"
},
"model_year": {
"type": "integer",
"description": "The model year"
},
"campaigns": {
"type": "array",
"items": {
"type": "string"
},
"description": "Every NHTSA campaign number the customer mentions, such as 24V123000"
}
},
"required": [
"make",
"model",
"model_year",
"campaigns"
]
}
}
}
],
"tool_choice": "auto"
}The response#
The reply to that request is a call, not an answer:
{
"model": "nenya-1",
"choices": [
{
"message": {
"role": "assistant",
"tool_calls": [
{
"id": "chatcmpl-tool-90adead5c5ed3d13",
"function": {
"arguments": "{\"make\": \"Ford\", \"model\": \"Escape\", \"model_year\": 2016, \"campaigns\": [\"25V695000\"]}",
"name": "find_recalls"
},
"type": "function"
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"completion_tokens": 27,
"prompt_tokens": 450,
"total_tokens": 477
}
}The loop runs find_recalls with those arguments, sends the result back, and the model answers. What the recipe printed, with the call the loop ran in the middle:
The contact owns a 2016 Ford Escape. The contact stated that while attempting to reverse, the rear-
view camera displayed a blank image, nearly causing the vehicle to crash with another vehicle. The
contact received notification of NHTSA Campaign Number: 25V695000 (Back Over Prevention); however,
the part to do the recall repair was not yet available. The contact stated that the manufacturer had
exceeded a reasonable amount of time for the recall repair. The approximate failure mileage was
171,237.
-> find_recalls({'make': 'Ford', 'model': 'Escape', 'model_year': 2016, 'campaigns': ['25V695000']})
Yes, the recall is on record for the 2016 Ford Escape. The remedy is that dealers will inspect and
replace the rearview camera as necessary, free of charge.Check it#
Two things can be checked exactly: the look-up the model asked for, against the complaint’s form, and the answer, against the record.
call, vehicle = looked_up[-1], customer["vehicle"] # the vehicle on the complaint's form: the test set's answer
record = [r for r in recalls_for(**vehicle) if r["NHTSACampaignNumber"] in campaign_numbers(customer["document"])][0]
print(f"looked up: {call['model_year']} {call['make']} {call['model']}, {call['campaigns']}")
print(f"the complaint's form: {vehicle['model_year']} {vehicle['make']} {vehicle['model']}")
print(f"the customer names: {campaign_numbers(customer['document'])}")
print()
print("NHTSA's record of the remedy:")
print(textwrap.fill(record["Remedy"], 100))looked up: 2016 Ford Escape, ['25V695000']
the complaint's form: 2016 Ford Escape
the customer names: ['25V695000']
NHTSA's record of the remedy:
Dealers will inspect and replace the rearview camera as necessary, free of charge. This will be a
phased campaign, with the remedy becoming available in different phases based on model and model
years. Interim letters notifying owners of the safety risk were mailed on October 25, 2025.
Additional letters will be mailed once the final remedy is available on each phase. Mustang owner
notification letters were mailed January 2, 2026. Owners may contact Ford customer service at
1-866-436-7332. Ford's number for this recall is 25SA9. Vehicle Identification Numbers (VINs)
involved in this recall became searchable on NHTSA.gov on October 14, 2025.The look-up is for the vehicle on the form and the number the customer wrote, and the answer’s remedy is the first sentence of NHTSA’s.
Three customers#
for customer in DATA["examples"]:
print(textwrap.fill(ask(customer["document"]), 100))
print()-> find_recalls({'make': 'Ford', 'model': 'Escape', 'model_year': 2016, 'campaigns': ['25V695000']})
Yes, the recall is on record for the 2016 Ford Escape. The remedy is that dealers will inspect and
replace the rearview camera as necessary, free of charge.
-> find_recalls({'make': 'Nissan', 'model': 'Leaf', 'model_year': 2022, 'campaigns': ['25V655000']})
Yes, the recall is on record for the 2022 Nissan Leaf (campaign 25V655000, Electrical system). The
remedy is that owners are advised not to use Level 3 quick charging until the remedy is completed,
and dealers will update the battery software free of charge.
-> find_recalls({'make': 'Ram', 'model': '2500', 'model_year': 2018, 'campaigns': ['24V896000']})
Yes, the recall is on NHTSA's record for the 2018 Ram 2500. The remedy is to have the hydraulic
control unit replaced (or the HCU motor replaced) at no cost.Three makes, three campaigns, each on record, each with the remedy its record gives: the camera, the battery software, the brake’s hydraulic control unit (the record writes “HCU”).
A recall that is not on record#
customer = DATA["not_on_record"]
print(textwrap.fill(customer["document"], 100))
print()
print(textwrap.fill(ask(customer["document"]), 100))The contact's ex-wife owns a 2012 Dodge Ram 1500. The contact stated that while his ex-wife was
driving at an undisclosed speed, the vehicle stalled. There was no warning light illuminated. The
driver shifted into park(P) and then restarted the vehicle. The contact stated that the starter and
key fob were replaced twice. The vehicle was not diagnosed or repaired by an independent mechanic or
dealer. The contact related the failure to NHTSA Campaign Number: 23V265000 (Power Train); however,
the VIN was not included in the recall. The manufacturer was not made aware of the failure. The
failure mileage was 165,353.
-> find_recalls({'make': 'Dodge', 'model': 'Ram 1500', 'model_year': 2012, 'campaigns': ['23V265000']})
The recall 23V265000 is not on NHTSA's record for a 2012 Dodge Ram 1500.NHTSA has no campaign 23V265000 for this truck, and the customer says as much: their vehicle “was not included”. (NHTSA files this truck as a “RAM 1500”. We looked there too: seven recalls, and this is not one of them.) The function found nothing and raised Final. The loop sent the sentence as the result, offered no tools on the next request, and the model told the customer.
That is how a look-up that finds nothing should end. A result that looks like an error, such as {"error": "not found"}, makes the model try again: in the API page’s tests it called again 96 times in 100 (After a result).
Why the tool takes the campaign number#
The first version of this recipe had a simpler tool. It took the vehicle, returned every recall the vehicle has, and left it to the model to find the one the customer meant:
LIST_TOOLS = [tool("list_recalls", "List the safety recalls NHTSA has on record for a vehicle.", VEHICLE,
["make", "model", "model_year"])]
def list_recalls(make, model, model_year):
"""The first version of the tool: every recall of the vehicle, for the model to find the right one in."""
records = recalls_for(make, model, model_year)
if not records:
raise Final(f"NHTSA has no recall on record for a {model_year} {make} {model}. Tell the user so, and ask "
"them to check the make, the model and the year.")
return [{"campaign": r["NHTSACampaignNumber"], "component": r["Component"].split(":")[0].capitalize(),
"remedy": r["Remedy"]} for r in records]
def ask_with_list(complaint):
return run_tools([{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"A customer writes:\n\n{complaint}\n\n{QUESTION}"}],
LIST_TOOLS, {"list_recalls": list_recalls})It is the obvious design, and it loses a quarter of the answers. A 2017 Ford F-150 has 18 recalls on record. Asked about campaign 26V237000 with all 18 in front of it, the model answered: “No. The listed recalls for the 2017 Ford F-150 do not include a recall for the transmission failure described.” The campaign is on the list.
The longer the list, the worse it went:
| The vehicle has | Complaints | Right with the whole list | Right with the recipe’s tool |
|---|---|---|---|
| Ten recalls or more | 13 | 8 | 13 |
| Fewer than ten | 16 | 14 | 15 |
| All | 29 | 22 | 28 |
The whole list also costs more: 1,816 prompt tokens a conversation on average and up to 3,211, against 1,197.
Finding a record by its number is a look-up, and code does not get a look-up wrong. Ask the model for the key (the vehicle, the number) and do the search yourself.
Measure it#
To count answers you need a rule for “the answer says what the records say”. Here it is a rule of thumb for English: a recall that is on record must not be denied, one that is not must not be confirmed, and no campaign number may appear that is in no record.
def says_none(answer):
"""Does an answer say that the recall is not on record? A rule of thumb for English, good enough to count with."""
return bool(re.search(r"(?i)^no\b|\bno (?:such |matching )?recalls?\b(?! repair| remedy| part)|"
r"\bnot (?:on|in|listed|found|appear|show|match|have)|did not turn up|no record", answer))
def agrees(answer, customer):
"""Does an answer say what the records say? A recall that is on record must not be denied, one that is not
must not be confirmed, and no campaign number may come from nowhere."""
if answer is None:
return False
on_record = {r["NHTSACampaignNumber"] for r in recalls_for(**customer["vehicle"])}
named = set(campaign_numbers(customer["document"]))
found = named & on_record
if set(campaign_numbers(answer)) - on_record - named:
return False # a number that is in no record and that the customer did not write
if not found:
return says_none(answer)
if found != named: # some are on record and some are not: it has to name the ones that are
return found <= set(campaign_numbers(answer))
return not says_none(answer)
def attempt(function, complaint):
"""An answer, without the lines run_tools prints. A conversation that fails counts as no answer."""
with contextlib.redirect_stdout(io.StringIO()):
try:
return function(complaint)
except (RuntimeError, TypeError, ValueError):
return NoneAll 29 complaints, with the recipe’s tool and then with its first version:
customers = DATA["sample"] # every complaint of the test set that names a recall and its vehicle
exact = said = 0
for customer in customers:
start = len(looked_up)
answer = attempt(ask, customer["document"])
calls, form = looked_up[start:], customer["vehicle"]
exact += (len(calls) == 1 and str(calls[0]["make"]).lower() == form["make"].lower()
and calls[0]["model_year"] == form["model_year"]
and recalls_for(calls[0]["make"], calls[0]["model"], calls[0]["model_year"]) == recalls_for(**form)
and calls[0]["campaigns"] == campaign_numbers(customer["document"]))
said += agrees(answer, customer)
listed = sum(agrees(attempt(ask_with_list, customer["document"]), customer) for customer in customers)
print(f"one look-up, for the form's vehicle and the customer's campaign numbers: {exact} of {len(customers)}")
print(f"the answer says what the records say: {said} of {len(customers)}")
print(f"the same with the first version, which returns the vehicle's whole list: {listed} of {len(customers)}")one look-up, for the form's vehicle and the customer's campaign numbers: 28 of 29
the answer says what the records say: 28 of 29
the same with the first version, which returns the vehicle's whole list: 22 of 29On the whole test set#
The 29 complaints are the whole set, so the numbers above are the measurement. We ran both tools twice and got the same 29 answers both times: the server decodes a request that has tools at temperature 0.
We also read the 29 answers of the recipe’s tool against the records, one by one, because a rule of thumb can be wrong. It was not: 28 say rightly whether the recall is on record, and each of the 27 that confirm one gives the remedy of its record. Three are loose with a detail. One drops “as necessary” from “replace the PTU, as necessary”. One calls the manufacturer’s own recall number a number to call. One says the battery software will be “replaced” where the record says it is updated.
The one miss: a customer with a 2024 Jeep Wrangler 4XE. The model wrote “Wrangler” in the call, NHTSA keeps the Wrangler 4XE as a model of its own, the look-up found nothing, and the answer said the recall was not on record. It is.
What the code caught along the way:
- Two calls passed the manufacturer’s own recall number next to NHTSA’s (“24S37”, “40D”).
campaign_numberskeeps what has the shape of an NHTSA number, so they were dropped. - Two calls wrote the model’s name longer than the records do (“XMAX 300”, “Promaster 3500”).
recalls_fordrops words from the end until something matches, so both were found.
What these records cannot say#
Five of the 29 customers write that their own vehicle was not included in the recall. A recall covers a vehicle by its VIN, and the records here are by model and year: they say that a campaign exists for the model and what its remedy is. One answer says “The vehicle is covered by NHTSA campaign 23V013000” to a customer who had been told the opposite. If your records cannot answer a question, have your code say so after the model’s answer (“Check your VIN at nhtsa.gov/recalls”), and do not leave that sentence to the model.
Make it yours#
- Ask the model for the key and do the search in code. That is the whole recipe.
- Return little. One record, not twenty. Every result is read again on the next request.
- Clean the arguments before you use them. Keep what has the right shape, forgive a longer name, and look at what your function was really called with.
- End a look-up that finds nothing with
Finaland a sentence that says what to tell the user. - Send the record with the answer when the detail matters. The model’s sentence is a summary of the remedy, and three of 27 summaries were loose.
- Keep the system message about what to do. “Always look the recall up first” is kept. A limit (“never promise a repair date”) belongs in your code.
Run it#
pip install openai
curl -O https://contrastivelabs.com/cookbook/tools-recall-lookup.py
curl --create-dirs -o data/tools-recall-lookup.json \
https://contrastivelabs.com/cookbook/data/tools-recall-lookup.json
python tools-recall-lookup.pyThe file is this page’s code in one piece: tools-recall-lookup.py. The complaints and NHTSA’s records are in data/tools-recall-lookup.json, each complaint with its link to NHTSA.