AI Coding Hallucinations: How to Stop Fake Packages and Unsafe Code
AI code can be wrong with confidence, fast. An AI coding hallucination is a plausible-looking package name, API call, or security rule generated without reliable support, and it can enter a build when developers mistake smooth prose for evidence. That is not harmless, especially in production.
AI coding assistants save time. They can draft tests, explain unfamiliar code, and suggest libraries in seconds. But a confident answer is not proof that the answer is true. A model may invent a package, use an API that changed years ago, or produce an access rule that grants far more power than the task needs.
The risk is not a reason to ban these tools. It is a reason to treat their output like any other untrusted input. In my experience, teams get the best results when they keep the speed of generated code but put firm checks around what can enter a build. That protects the software and the people who depend on it.
What Are AI Coding Hallucinations?
An AI coding hallucination is generated output that sounds correct but is false, unsupported, or unsafe. A language model predicts likely next words or code tokens from patterns it learned during training. It does not automatically check every answer against a live package registry, current product manual, or security standard. When the model lacks a dependable pattern, it may fill the gap with something that merely looks right.
That distinction matters. A normal coding mistake might be a wrong variable name or a failed test. A hallucination can be more slippery: the import has a believable name, the function signature matches the style of the SDK, and the explanation sounds calm and precise. The code may even compile. None of that proves that the package, behavior, or security claim is real.
Common forms include package hallucinations, where an assistant recommends a library that does not exist; API hallucinations, where it invents a function or uses an old signature; and security hallucinations, where it presents a weak or outdated control as safe. There are also factual errors about how a framework works. These problems can overlap in one answer.
I have reviewed generated code where an import looked so much like the surrounding libraries that it seemed ordinary at first glance. The useful check was not whether the name looked familiar; it was whether the official registry and the project documentation confirmed it. That small pause can catch a mistake before it becomes a dependency.

Code makes this harder than ordinary prose. A compiler can catch some syntax and type errors, but it cannot tell you that a new package is controlled by an unknown party, that an authentication flow invites phishing, or that a cloud policy grants broad access without a business reason. Passing tests is helpful. It is not a security review.
A model can also produce different kinds of errors in the same patch. It might import a real library, call a made-up method, and then explain the behavior incorrectly. Reviewers should check the claim, not just the code around it. The key question is simple: what trusted evidence supports this suggestion?
Why AI Hallucination Risk Matters
The main benefit of noticing hallucinations is not fear. It is control. Teams can use an assistant for routine drafting while keeping risky choices—such as new dependencies, authentication, cryptography, and cloud permissions—inside a clear review process.
- It protects the software supply chain. A dependency is executable code from outside your project. Checking its name, maintainer, version history, and source before installation helps stop a made-up package from becoming trusted code. A lockfile and a known registry give reviewers a trail to inspect.
- It makes review more useful. A reviewer who knows that generated code can invent an API will check the official documentation rather than spend time admiring tidy formatting. I have seen a short registry check answer a question that several rounds of code review had left open.
- It keeps permissions narrow. Generated cloud policies can request broad access because broad access is an easy way to make an example work. Asking whether each permission is needed—and testing the policy—can prevent a small feature from receiving control it does not require.
- It protects accounts and private data. Authentication advice has real consequences. A pattern that looks familiar may not fit current threats or current guidance. Teams should rely on reviewed standards and security specialists for high-impact decisions, not on a chatbot’s confident tone.
- It makes productivity gains measurable. Track how often suggestions fail registry, test, or security checks. That tells a team whether a tool is helping in its own codebase, rather than asking people to trust a general claim about AI.
The published package-hallucination research is a warning, not a prediction for every company. In one study, researchers tested 16 code-generating models and found that about one in five recommended dependencies in their test setting referred to packages that did not exist. They reported more than 205,000 distinct fabricated package names across the test set. Those results show that the behavior can be repeated; they do not mean one in five suggestions from every tool or prompt will be false.
There is a human reason to care, too. Software handles people’s work, money, health records, and private conversations. Treating those systems with care is ordinary professional responsibility. In practice, that means assigning a real person to approve consequential changes, even when an assistant drafted most of the code.
How to Build Guardrails Into the Development Workflow
A good control is specific, repeatable, and close to the point where risk enters. Here is a practical sequence I would use for a team adding an AI coding assistant.
- Mark the high-risk areas. Identify code that handles sign-in, account recovery, payment, personal data, cryptography, or cloud access. Set a stronger review rule for those paths. A small wording change in a test helper is not the same risk as a new login flow.
- Verify every new dependency. Before installation, check the exact package name in the official registry, then confirm that the project documentation describes the API being used. Check for spelling lookalikes, unexpected ownership changes, thin release histories, and suspicious install scripts. Do not let a plausible name count as evidence.
- Use an allowlist where it makes sense. For production services, limit dependency sources to approved registries and, when practical, approved packages. Review changes to
package.json, requirements.txt, and similar manifests. Keep lockfiles in version control so the exact versions and dependency tree are visible during review. - Make the pipeline check the work. Run tests, dependency and license checks, static analysis, secret scanning, and policy checks in continuous integration. Block unapproved registries or packages when the project’s risk calls for it. A reviewer should see a clear failure when a dependency cannot be verified, not a buried warning after release.
- Ground security decisions in current guidance. For identity, use documentation and standards that your security team has reviewed. The NIST Digital Identity Guidelines describe authentication requirements, while the FIDO Alliance passkey resources explain how passkeys use public-key cryptography and resist phishing. A passkey is not a magic fix for every account, but it is a stronger option to consider for important sign-ins than relying on a model’s example.
- Use retrieval carefully. Retrieval-augmented generation can provide an assistant with approved documentation at answer time. That may reduce errors caused by stale training data, but it does not guarantee that the model used the right page or interpreted it correctly. Keep links to the source and ask reviewers to confirm that the suggested behavior matches it.
- Measure the misses. Record rejected package suggestions, incorrect API calls, security findings, and review time. Group results by tool, language, and task. This turns a vague concern into a trend that a team can act on. The published study of package hallucinations offers a starting point for thinking about repeatable tests, though each team should measure its own tools and code.
I once found that a generated change could pass its unit tests while asking a cloud role for permissions the feature did not need. The fix was not a longer prompt. We narrowed the permissions, added a policy check, and made that check visible in review. Automation helped because it did not depend on the next reviewer remembering the same warning.

AI Hallucinations Versus Traditional Typosquatting
Slopsquatting is a supply-chain attack that takes advantage of fabricated package suggestions. An attacker watches for package names that code models tend to invent, registers a name in a public registry such as PyPI or npm, then waits for a developer or automated workflow to install it. If the package is malicious, its code may run with the permissions of the build environment.
Traditional typosquatting relies on a developer mistyping a real package name or confusing it with a similar one. Slopsquatting skips the typo: the name may be suggested by the assistant itself. The attack can be hard to spot because a name may recur across prompts, rather than being a one-off random error.
| Risk factor | AI hallucination and slopsquatting | Traditional typosquatting |
|---|
| How the name appears | An assistant invents a plausible package name | A person mistypes or misremembers a package |
| Attacker’s opportunity | Register a name that models repeatedly suggest | Register a name close to a popular package |
| Typical warning sign | No trusted documentation or an unexpected package owner | A lookalike spelling, odd owner, or unfamiliar package |
| Useful first check | Confirm the exact name in the official registry | Compare the spelling with the package’s official page |
| Stronger controls | Allowlisted sources, dependency review, CI checks | Dependency review, lockfiles, registry safeguards |
The research figures above need context. The study tested 16 models and counted more than 205,000 fabricated names across its test set; its estimate of roughly one in five applied to the study’s conditions, not every coding assistant in daily use. Still, the scale matters because an attacker does not need every name to work. A repeatedly suggested package can remain a target for as long as a model continues to produce it.
Neither attack is solved by a lockfile alone. A lockfile can record exactly what was installed, which is valuable for review and repeatable builds, but it cannot prove that the first installation was safe. Verify the package before it enters the project, then preserve that decision in the repository and pipeline.
Common Mistakes to Avoid
A lot of advice says to review AI-generated code. Fine—but that phrase is too broad to be useful on its own. Reviewers need to know what to check, what evidence counts, and which changes need extra care.
- Mistaking clean code for correct code. Good formatting and a helpful explanation can make a false claim feel trustworthy. Check the registry, official API documentation, and version-specific behavior. A polished answer is still only a suggestion.
- Treating a successful build as proof of safety. Compilation and tests check particular conditions. They do not prove that an authentication design resists phishing or that a cloud policy follows least privilege. Ask what the tests cover and what they leave out.
- Installing first and checking later. Package installation can run scripts and pull in more dependencies. Verify a new package before running its install command, especially in a privileged developer machine or build runner.
- Assuming a lockfile fixes everything. Lockfiles help pin versions and support repeatable builds. They do not judge whether a package is appropriate, trustworthy, or malicious. Pair them with registry checks and review of new dependencies.
- Asking the same model to certify its answer. A second prompt can help find questions to investigate, but it is not an independent security review. Use primary documentation, a second tool with a different role, or a qualified reviewer for important decisions.
- Believing retrieval removes hallucinations. A model can misread a real document, use a page for the wrong version, or make a claim the document does not support. Keep the cited source visible and confirm it says what the code claims.
- Leaving checks to human memory. People miss things, especially when a patch is large and the delivery date is close. Put repeatable rules in continuous integration and keep a person responsible for exceptions.
OWASP’s Top 10 for Large Language Model Applications includes misinformation as a risk area. That is a useful reminder to check outputs against reliable sources rather than treating fluent answers as facts. NIST’s Generative AI Profile also gives organizations a framework for considering risks across design, use, and review. Neither reference replaces practical tests in your own pipeline.
The simplest mistake is pretending this is only a prompt-writing problem. Better prompts can help, but they cannot guarantee that a dependency exists or that a security pattern is current. Put checks where code is installed, tested, and released. That is where the risk becomes concrete.
Frequently Asked Questions
Are all AI-generated code suggestions hallucinations?
No. Many suggestions are useful and correct. A hallucination is output that is false or unsupported but presented as if it were reliable. The trouble is that a correct suggestion and a fabricated one can look equally polished. Verify claims that affect dependencies, security, or production behavior instead of judging them by tone.
How can I check whether an AI-recommended package is real?
Search the exact package name in the official registry, then open its project documentation and verify that the API in the generated code exists for the version you plan to use. Check the maintainer, release history, source repository, and install behavior. If the package cannot be confirmed through trusted sources, do not install it just to see what happens.
Can AI-generated code be secure?
It can be part of secure software, but the code needs the same review and testing as code written by a person. Run appropriate tests and security tools, check dependencies, and get qualified review for authentication, cryptography, permissions, and sensitive data. A model’s confidence, tests, or explanation alone cannot certify security.
Does retrieval-augmented generation prevent hallucinations?
No. Retrieval can give a model current, approved documents to use, which can reduce some errors caused by stale or missing information. But the model may still select the wrong document, misread it, or state more than the source supports. Keep the cited material available and verify important claims against it.
Final Thought
AI coding tools can make useful work faster. They can also produce a convincing mistake faster than a person can notice it. The answer is not to distrust every line or to treat every model as an enemy. It is to set clear boundaries: verify new packages, keep permissions narrow, test the code, and require careful review where a mistake could harm people.
I have learned that a small automated check often beats a long warning in a team handbook. If a dependency is unknown, make the pipeline say so. If a permission is too broad, fail the policy check. If a security decision affects real users, ask a qualified person to own it. These are ordinary engineering habits, applied to a new source of code.
Good software work is a form of stewardship. The systems we build carry other people’s trust, so speed should serve that duty rather than replace it. Keep the useful assistance, keep human judgment in the loop, and make the safe path the easy path.