Sub topic 3
Why Language Models Invent Package Names
This chapter explains the mechanism behind hallucinated package names. It assumes you have used pip or npm, have asked an AI assistant for code, and can run Python scripts. Earlier chapters covered how a package name becomes installed code. This one covers why the name an assistant suggests may not exist.
What a model actually does when it writes a name
A large language model (LLM) generates text one token at a time. A token is a short chunk of text, often a word fragment. At each step the model assigns a probability to every possible next token and picks one, according to its sampling settings.
The model does not look names up in a registry while it writes. It has no list of what PyPI or npm contains. It has learned statistical patterns from training text, and those patterns include what package names look like. When you ask for code that parses a particular file format, the model produces a name that fits the context. That name is often right, because common packages appear in its training data thousands of times. The same process can produce a name that has never existed.
Two properties of this process matter for security:
- The goal is plausibility, not existence. The model optimizes for text that looks like its training data. A fabricated name such as
flask-jwt-helperlooks as natural as a real one such asflask-jwt-extended. - Confidence is not evidence. The model writes a real name and an invented name in the same fluent tone. The tone gives you no signal about which one you got.
Why the invented names look so believable
Package names are not random. They follow conventions, and a model learns those conventions well. That makes invented names hard to spot by eye.
- Prefix and suffix patterns. Flask extensions are usually named
flask-something. Many Python libraries start withpyor end with-client,-utils, or-sdk. A model can combine a known framework with a plausible feature word. - Ecosystem conventions. npm names often use scopes such as
@angular/core. Python names often use hyphens where the import name uses underscores. - Descriptive naming. Many real packages are named for what they do. A name like
pandas-excel-formatterdescribes a function a developer might want, so the model can produce it on demand even when no such package exists.
The model is effectively generating a name that would fit in the registry. Whether it fits and whether it exists are separate questions.
Common causes of hallucinated names
Several distinct situations lead to a nonexistent or wrong name. Knowing them helps you judge which suggestions need extra scrutiny.
Import name versus distribution name
In Python, the name you import is often different from the name you install. The install name is called the distribution name.
| You write | You install |
|---|---|
| `import yaml` | `pip install pyyaml` |
| `import cv2` | `pip install opencv-python` |
| `import sklearn` | `pip install scikit-learn` |
| `import PIL` | `pip install pillow` |
A model that sees import sklearn in training data may suggest pip install sklearn. That is a real, historic problem. For years the name sklearn on PyPI was a placeholder that did not install the library, and the maintainers of scikit-learn eventually made it fail with an explanatory message. Mapping an import to the wrong install name is one of the easiest mistakes for a model to make, because the training text shows both names in different places.
You can see this mapping for packages you already have installed. This script uses importlib.metadata.packages_distributions(), available in Python 3.10 and later.
from importlib.metadata import packages_distributions
mapping = packages_distributions()
for import_name in ("yaml", "cv2", "sklearn", "PIL"):
dists = mapping.get(import_name)
if dists:
print(f"import {import_name!r} is provided by distribution(s): {dists}")
else:
print(f"import {import_name!r}: not provided by any installed package")The output depends on what is installed in your environment. For example, if PyYAML is installed, the yaml line shows ['PyYAML']. The point is that the two names differ, and a model has to remember each mapping separately.
Rare or niche libraries
Training data contains far more text about popular packages than about niche ones. When you ask about a specialized task, such as a particular lab instrument protocol or an uncommon file format, the model has few examples to rely on. It may recall the topic but not the exact name, and it fills the gap with a plausible guess. Hallucinations tend to concentrate in these low-frequency areas.
Outdated, renamed, or removed packages
Training data has a cutoff date. Packages get renamed, merged, deprecated, or deleted after that date. A model may suggest a name that existed once and no longer does. If the name was deleted from the registry, it may be available for anyone to register again, depending on the registry's rules. A past real name and a never-real name carry the same risk once the name is free.
Cross-ecosystem confusion
A model learns from many languages at once. It may suggest an npm-style name in a Python project, or the reverse. A package can exist on npm and not on PyPI. If the name is free on the other registry, it is a target there.
Confusing a repository, tool, or concept with a package
Code in training data refers to GitHub repositories, command-line tools, cloud services, and internal modules. A model can turn any of these into an install command. A tool name such as huggingface-cli is a command, not a package, but a model may suggest installing it by that name. A security researcher registered an empty package under that name in 2023 and reported that it was downloaded tens of thousands of times in a few months. The download count shows how much traffic one believable but wrong suggestion can generate.
Sampling and context effects
Settings and context change how often invented names appear:
- Higher temperature, which makes sampling more random, increases the chance of unusual tokens, including unusual package names.
- A long or vague prompt gives the model less to anchor on.
- If you ask for a package that does something specific, the model is under pressure to produce one. It may invent a name instead of saying that no such package exists.
How common is it, and how repeatable
Researchers have measured this. A 2024 study by Spracklen and colleagues generated a large set of code samples, over half a million, from many models, and checked each suggested package against the registries. They reported that on average about one in five suggested packages in their Python and JavaScript tests did not exist. Commercial models did better than open-source models, with a lower but still nonzero rate. Treat the exact percentages as results from one study with specific prompts and models. Rates differ by model, version, task, and language.
The finding that matters most for security is repeatability. The same study found that many hallucinated names came back when the same prompt was run several times. A large share appeared in every repeat run. If a model invented a name once and never again, an attacker could not plan around it. Because the same names recur, an attacker can ask a model the same kinds of questions developers ask, collect the nonexistent names that come back, and register the ones that repeat.
You can measure the repeat rate on your own data. This script takes names suggested across several runs of the same prompt, together with the set of names you have confirmed exist, and reports which nonexistent names repeat. The data here is made up for illustration.
from collections import Counter
# Names an assistant suggested across five runs of the same prompt (illustrative).
runs = [
["requests", "flask-jwt-helper", "pyyaml"],
["requests", "flask-jwt-helper"],
["requests", "yaml-fastparse", "pyyaml"],
["requests", "flask-jwt-helper", "pyyaml"],
["requests", "pyyaml"],
]
# Names you have verified exist on the registry (illustrative).
known_to_exist = {"requests", "pyyaml"}
counts = Counter(name for run in runs for name in set(run))
missing = {n: c for n, c in counts.items() if n not in known_to_exist}
for name, count in sorted(missing.items(), key=lambda item: -item[1]):
print(f"{name}: suggested in {count} of {len(runs)} runs, not found on registry")Running it prints flask-jwt-helper with a count of 3 and yaml-fastparse with a count of 1. A name seen in most runs is a better target for an attacker than one seen once.
Why this is hard to fix inside the model
It is tempting to expect that a better model will stop inventing names. Newer models do hallucinate less, but several things keep the problem from vanishing:
- The model has no built-in registry. A snapshot of names in its training data goes stale, and registries add thousands of packages every day.
- Training rewards fluent, helpful answers. A model that answers "I don't know a package for that" can score worse in some evaluations than one that gives a confident name.
- Rare topics will always have sparse training data.
- Tools that let a model search the web or check a registry reduce the problem, but only when they are enabled and used correctly. A later chapter covers these model-side and tooling mitigations.
For you as a developer, the practical conclusion is that a package name from an assistant is a claim to verify, not a fact. A later chapter shows how to verify it. For now, the working habit is to treat each new name the same way you treat a link from an unknown sender.
Signals that a suggested name deserves a closer look
Some patterns raise the odds that a name is invented or wrong. None is proof, and an experienced developer should still check names that look fine.
- You have never seen the name in documentation, tutorials, or other projects.
- The name is a long, descriptive combination of a framework and a feature.
- The name is a command-line tool or service name used as an install target.
- The install name equals the import name for a library where you remember them differing.
- The suggestion came from a long answer about an unusual task.
- The assistant suggested a new package when the standard library or an existing dependency already covers the task.
Summary
A language model writes package names by predicting likely text, not by consulting a registry. That makes invented names plausible and fluent. Common causes include mismatched import and install names, rare libraries, stale training data, mixing ecosystems, and treating tools or repositories as packages. Studies show the problem is frequent and, importantly, repeatable, which is what makes it exploitable. The next chapter shows how an attacker uses those repeating names.
Exercise
An assistant tells you to run pip install sklearn and, in the same answer, pip install flask-session-manager-pro. For each command, name the most likely reason it could be wrong, and say what you would check before running either one.
Show answer
sklearn is an import name, not the distribution name. The library installs as scikit-learn, so the model likely mixed up the import name and the install name. flask-session-manager-pro is a long descriptive name that combines a framework with a feature, which is the pattern models produce when they invent a name that fits conventions. Before running either, look the name up on the registry (for example the PyPI page or its JSON API), and confirm that the project's own documentation lists that install name. For the second name, also check how many releases it has, when it was first uploaded, and whether it links to a real source repository. If the name does not exist, or is brand new with little history, do not install it.
Exercise
Why does the fact that the same hallucinated names come back across repeated runs of a prompt matter more for security than the overall hallucination rate?
Show answer
An attacker can only profit from a name if developers are likely to be told it. If invented names were random and different each time, registering any one of them would rarely catch a victim. Because many names repeat, an attacker can query models with common developer questions, collect the nonexistent names that recur, and register those names, which makes later installs by developers and coding agents likely.