Sub topic 10
What Model and Tool Builders Can Do
This chapter covers what the people who build coding models and coding tools can do about hallucinated package names. Earlier chapters covered why models invent names and how an attacker registers them. Here you look at the other side of the chain: where a model or tool can stop a bad name before it reaches a terminal. It assumes you know how pip and npm resolve names from a public registry. It also assumes you have used an AI coding assistant, and that you can read short Python.
Why builder-side defenses matter
A developer can verify every package by hand, but that depends on discipline, and discipline fails under deadline pressure. Builders sit earlier in the chain. A fix in a model or an assistant applies to every user, including those who never read a chapter like this one.
Builder-side defenses also have a limit. They lower the rate of bad suggestions but cannot bring it to zero, because the root cause is how language models work. A model predicts plausible text. A plausible package name, such as flask-jwt-helpers, is exactly what such a model produces when it has no firm memory of a real one. Treat builder-side measures as one layer. The checks and controls in other chapters still apply.
Research on this problem measured a wide spread. One large 2024 study sampled hundreds of thousands of generated code snippets across many models. It found that a noticeable share of suggested packages did not exist, and that open-source models hallucinated more often than commercial ones. The exact figures vary by model, prompt, and language, so use them only as evidence that the rate is not negligible. A rate of a few percent is still large when millions of suggestions are generated.
The next diagram shows the points where a builder can intervene.
Model-side mitigations
These changes happen in the model or in how it is prompted. They reduce how often a fake name appears at all.
Training and fine-tuning
A model hallucinates a package name when it was never taught that the name is wrong. Builders can fine-tune on examples where the correct behavior is to pick a real, well-known package, or to say it is unsure. Some work has also tried training against lists of known-good packages. The reported effect is a lower hallucination rate, but with a cost. In some experiments, code quality dropped after tuning aimed at the hallucination rate, because the model became more conservative. This is a real trade-off to weigh, not a free fix.
Training data also matters. If the data contains repositories that reference packages that were later deleted or never existed, the model learns those names as real. Curating training data against registry snapshots removes some of this noise.
Grounding with retrieval
Retrieval-augmented generation (RAG) gives the model facts at generation time instead of relying on memory. For packages, the facts come from a registry index. The tool looks up candidates that match the task, and the model chooses from that list. A model that picks from a retrieved list of real packages cannot invent one unless the prompt lets it.
Grounding has two failure modes:
- The index is stale. A package deleted last week still appears, and a freshly registered malicious package looks legitimate.
- The index contains the attacker's package. A registry listing proves existence, not trust. Retrieval must carry trust signals, not only names.
Self-checking and consistency
Models can be asked to review their own output. A second pass reads the generated code, lists every package it imports, and asks whether each is one the model is confident exists. This catches some errors, but it is weak when the model's confidence is itself wrong.
Another signal comes from sampling. If you ask the same question several times and a package name appears in only one answer, the name is more likely a guess. Names that recur across many samples are more likely real. The same research found that some hallucinated names recur consistently, and this matters for security. A repeated fake name is the one an attacker would register. So consistency lowers noise from random guesses, but it does not remove the repeated fake names that attackers target.
Expressing uncertainty
A model that says "I'm not sure this package exists, verify it first" is more useful than one that states a wrong name confidently. Builders can tune for this behavior. The weakness is that users learn to ignore constant disclaimers. Uncertainty notes work better when they appear only for names the system cannot confirm.
Tool-side mitigations
The tool wraps the model. It is the better place for hard guarantees, because it can check facts the model cannot know.
Verify names against the registry before display
The simplest tool-side control is a lookup. Before showing a suggestion, or before running any install, the tool asks the registry whether the package exists. A missing name is a hallucination, and the tool can drop it, replace it, or flag it.
This check has a hole. A missing name today can be registered tomorrow, and the attack depends on this. A check that only answers "does it exist?" passes the attacker's package once it is published. The tool needs more signals than existence:
- Age. The date of the first upload. A package created last week that a model recommends for a decade-old task is suspicious.
- Release history. One release with no later updates is weaker evidence than a long history.
- Popularity. Download counts and dependents. These can be inflated, so use them as one signal and not as proof.
- Source linkage. Whether the listed repository exists and links back to the package.
- Known advisories. Whether the package or maintainer appears in malware reports.
None of these is decisive alone. A tool scoring several together is much harder to fool than one checking a single value.
Handle the name mapping problem
In Python, the name you import is often not the name you install. You write import yaml but install PyYAML. You write import cv2 but install opencv-python. A tool that converts import statements to install commands must map import names to distribution names. A naive guess such as "install a package called yaml" can itself land on an unrelated or malicious package. Use a maintained mapping, or read it from metadata of installed distributions, and never infer an install name from an import name alone.
Gate installs in agents
Coding agents can run pip install or npm install on their own. This removes the human who might have noticed a strange name, so agent builders should treat package installation as a privileged action:
- Require approval for any install of a name not already in the project's lockfile.
- Run installs in a sandbox with no access to credentials, SSH keys, or cloud tokens.
- Disable lifecycle scripts by default, for example with
npm ci --ignore-scripts, and ask before enabling them. - Show the user the package name, its age, and its release count at the approval prompt, not just a yes or no.
- Log every install decision so an incident responder can reconstruct what ran.
A working example: a suggestion checker
The script below is a small version of a tool-side guard. It takes the package lines a model suggested, looks up each name, and returns a verdict. The lookup function is a parameter, so the logic can be tested offline. The demo at the bottom uses a fake registry, so it runs without network access. To use it for real, pass fetch_first_upload as the lookup.
import json
import re
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
MIN_AGE = timedelta(days=30)
def fetch_first_upload(name):
"""Return {'first_upload': datetime or None}, or None if the package is missing."""
url = f"https://pypi.org/pypi/{name}/json"
try:
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.load(resp)
except urllib.error.HTTPError as err:
if err.code == 404:
return None
raise
times = [
datetime.fromisoformat(f["upload_time_iso_8601"].replace("Z", "+00:00"))
for files in data["releases"].values()
for f in files
]
return {"first_upload": min(times) if times else None}
def check(line, lookup, now, allowlist=frozenset()):
match = NAME_RE.match(line.strip())
if not match:
return "reject: not a valid package name"
name = match.group(0)
if name.lower() in allowlist:
return "allow: already approved for this project"
info = lookup(name)
if info is None:
return "block: not on the registry (likely hallucinated)"
first = info["first_upload"]
if first is None:
return "block: registered but has no files"
if now - first < MIN_AGE:
return f"hold: first published {(now - first).days} days ago, needs human review"
return "allow: exists and is established"
if __name__ == "__main__":
now = datetime(2026, 11, 28, tzinfo=timezone.utc)
fake_registry = {
"requests": {"first_upload": datetime(2011, 2, 14, tzinfo=timezone.utc)},
"fresh-helper": {"first_upload": datetime(2026, 11, 20, tzinfo=timezone.utc)},
}
lookup = fake_registry.get
for line in ["requests>=2.0", "fresh-helper", "made-up-pkg", "-bad"]:
print(f"{line}: {check(line, lookup, now)}")Running it prints one verdict per line. requests>=2.0 is allowed. fresh-helper is held for review because it is 8 days old. made-up-pkg is blocked as missing, and -bad is rejected as an invalid name. Note that the verdicts are three tiers, not two. The "hold" tier matters most, because it covers the case an attacker aims for: a name that exists but was only just registered.
Limits and trade-offs
No single builder-side measure is sufficient. The table compares them.
| Measure | What it prevents | Main weakness |
|---|---|---|
| Fine-tuning on real packages | Random fake names | Can reduce code quality; does not stop repeated fake names |
| Retrieval from a registry index | Invented names | Stale index; listing is not trust |
| Self-check and sampling consistency | Some one-off guesses | Confident errors pass; repeated fakes pass |
| Registry existence check | Names that do not exist yet | Passes a name once an attacker registers it |
| Age and history signals | Freshly registered malicious packages | An attacker can wait out the age threshold |
| Install gates and sandboxing | Damage from a bad install | Adds friction; users may approve without reading |
An attacker who knows the age threshold can register a name and wait. This is why age checks must be combined with other signals and why sandboxing matters. Sandboxing limits harm even when a bad package gets through. Builders should also expect an arms race. As the checks become public, attackers adapt, for example by publishing a harmless version first and adding the payload in a later release. For this reason, a tool should re-check packages when versions change, not only at first suggestion.
Common mistakes when building these defenses
- Treating "exists on the registry" as "safe." Existence is the attacker's goal.
- Checking only at suggestion time. A name can be harmless when suggested and malicious by install time.
- Mapping import names to install names by string equality in Python.
- Showing warnings on every suggestion, so users stop reading them.
- Letting an agent install packages with the user's full credentials in the environment.
- Caching registry results for too long, which hides a package that was newly taken over or yanked.
Exercise
A coding assistant checks every suggested package against PyPI and only shows names that exist. An attacker notices that the model often suggests data-cleanse-utils, which does not exist, and registers it. Why does the existence check fail here, and name two additional signals the assistant could use to catch it?
Show answer
The check only asks whether the name exists, and after the attacker registers it, the answer is yes. Existence does not show trust. The assistant could add the age of the first upload (a package published days ago stands out), the release history (a single release with no updates), download counts or dependents, a missing or unlinked source repository, or malware advisories. A holding tier for new or sparse packages that asks for human review is the practical response. Sandboxing and disabling install scripts would limit harm even if the package got through.
Exercise
In the example script, fresh-helper returns a "hold" verdict instead of "block". Why use a separate tier for new packages, and what could an attacker do to get around the 30-day threshold?
Show answer
New packages are not necessarily malicious, since legitimate projects are new at some point, so blocking all of them would reject real work. A hold tier sends them to human review instead. An attacker can wait out the threshold, or publish a harmless first release and add the payload in a later version. To handle this, the tool should re-check on version changes, combine age with other signals, and install inside a sandbox.