AI coding assistant hallucinations are false but convincing outputs—such as invented packages, stale security advice, or excessive cloud permissions—that...
AI Coding Assistant Hallucinations: How to Catch Fake Packages and Unsafe Code
AI coding assistant hallucinations are false but convincing outputs—such as invented packages, stale security advice, or excessive cloud permissions—that can slip into working software. They happen because a model predicts plausible text, not because it has verified every claim. Treat each suggestion as untrusted until tested against trusted sources.
I’m Ermenildo Valdez Castro, Jr., and years of building and reviewing software have taught me a plain rule: code that looks tidy can still be wrong in expensive ways. AI assistants speed up the first draft, but they do not take responsibility for what that draft does. A pleasant explanation is not evidence. A green build is not proof of safety.
The risk is not that every generated line is dangerous. Most suggestions are ordinary, and many save time. The trouble starts when a team treats fluency as verification, especially in dependency management, authentication, cryptography, and cloud access. A made-up package may install. A weak login flow may pass a basic test. A broad cloud permission may work perfectly—while granting far more access than the service needs.
That is why the right response is neither panic nor blind trust. Keep the useful speed, then add checks where software enters the build and where security decisions are made. This is practical stewardship: protect the people who rely on a system, including customers who never see the code review.
What Are AI Coding Assistant Hallucinations?
An AI coding assistant hallucination is an output that sounds plausible but contains a false claim or fabricated detail. In software work, that might be a package that does not exist, an API method with an invented name, a code sample that uses the wrong argument order, or a security recommendation that no longer meets current guidance. The model may present any of these with the same calm tone it uses for correct information.
Most language models generate text by predicting likely next tokens from patterns learned during training. They do not automatically check a package registry, read the latest vendor manual, or confirm that an authentication method is safe for your use case. Some products can search documentation or call tools, but those features only help when they are configured correctly and their results are checked. Without verification, a plausible completion can fill a gap in the model’s knowledge with a convincing guess.
Code makes that guess harder to spot. Real package names and function signatures follow familiar naming patterns, so fabricated ones can look right at a glance. A compiler checks whether code follows the language’s rules; it does not prove that a dependency is trustworthy, that an API is supported, or that a permission is appropriate. Tests help, too, but they only cover the behavior they actually test.
I have seen reviewers spend time checking formatting and variable names while a more basic question sat untouched: does this function exist in the version we use? In one code review, a generated call looked consistent with the surrounding SDK. The team checked the vendor documentation and found the name was not part of that release. Catching it took minutes. Finding it after deployment would have taken longer.
Keep three problems separate. A hallucination is an inaccurate output, whether or not anyone meant harm. A software bug is a defect in behavior. An attack occurs when someone deliberately exploits a weakness, such as registering a fake package name after seeing models suggest it. These can overlap, but they are not the same thing. That distinction matters because a harmless-looking error can create an opening for a deliberate attack.
Why AI Hallucinations Matter for Software Security
The concern is not limited to strange code that fails to compile. An assistant can influence what enters a dependency tree, how a login flow handles identity, and which resources a cloud service can reach. Those choices affect real users and production systems. Frankly, the speed of generation makes a weak review habit more costly, not less.
- Package suggestions can expose a build. A study of 16 code-generating models found that about one in five recommended dependencies in the study pointed to packages that did not exist. Researchers reported more than 205,000 unique fabricated package names across their test set. These findings are study results, not a claim that one in five package suggestions in every workplace is fake. Still, the pattern is serious enough to check. The researchers describe their analysis in a study of package hallucinations by code-generating models.
- Fake package names can be turned into a trap. An attacker can watch for commonly hallucinated names, register one on a public package registry, and wait for a developer to install it. Researchers call this pattern slopsquatting: instead of relying on a developer’s typo, the attacker bets on a model’s invented package name. A package install may run scripts or add code that later executes in a build environment, where secrets and write access may be available.
- Security advice can be stale or incomplete. A generated login example may use SMS codes without explaining their limits, or present a weak session design as a complete solution. For accounts that need stronger protection, phishing-resistant passkeys or security keys are often better choices. The FIDO Alliance explains how passkeys work and help resist phishing. The details still matter: teams must consider account recovery, device loss, and the risk level of the account.
- Cloud permissions can quietly grow. Generated IAM policies may grant broad actions or access to resources that the task never required. The code may work, which makes the excess permission easy to miss. Least privilege is not busywork; it limits the damage if a service or credential is compromised.
- The reviewer’s attention has a limit. I have worked with teams where a fast, polished change drew less scrutiny than a rough one. That is a human habit, not a special failure of AI. When suggestions arrive quickly and in large volume, relying on someone to notice every weak detail is wishful thinking. Review must be backed by automated checks.
How to Reduce AI Coding Assistant Hallucinations: A Step-by-Step Guide
Use AI as a drafting tool, not as an authority. The process below keeps useful suggestions moving while checking the places where a bad guess can cause real harm.
- Set rules for high-risk code before prompting. Define which areas need extra review: dependencies, authentication, authorization, cryptography, payments, customer data, and infrastructure permissions are common examples. Decide who approves changes in those areas and which automated checks must pass. If a team has no shared rule, each reviewer ends up guessing what deserves attention.
- Verify every suggested package at its source. Search the official registry, confirm the exact package name, check the publisher and project history, and read the documentation for the version you plan to use. A package’s existence is only the first check; an attacker can register a real name. Look for suspicious ownership changes, very recent publication, unusual download patterns, and unexpected install scripts. For a critical dependency, compare the registry entry with the project’s official repository.
- Use dependency controls in the pipeline. Keep approved package lists where they make sense, pin versions, review lockfile changes, and use tools that flag known vulnerabilities and risky package behavior. An import check can quickly catch a name that does not exist in an approved registry, but it cannot tell you that a registered package is safe. Treat validation as a set of layers, not one magic scan. The NIST Secure Software Development Framework offers practices for building security checks into software development and release work.
- Ask for evidence, not confident wording. When an assistant recommends a package or API, ask it for the official documentation page and version. Then open that page yourself. A link produced by the model can also be wrong, so verify the domain and content. If the documentation does not support the claim, do not keep the code merely because it compiles.
- Review security logic against current guidance. For authentication, check enrollment, recovery, rate limits, session handling, and phishing resistance—not just the happy-path login. For cryptography, confirm algorithms and parameters against current guidance instead of accepting a sample copied from old code. For cloud access, map every permission to a specific action the service must perform. I once saw a generated policy solve a test failure by granting wide access; it fixed the immediate error and created a larger security problem. The right fix was to identify the one missing action.
- Test behavior and abuse cases. Unit tests show whether a function behaves as expected for chosen inputs. Add tests for denied access, malformed data, expired sessions, replay attempts, and other relevant failure paths. Use static analysis and security scanners as well, but read their findings. A tool can surface likely problems; it cannot understand every business rule or replace an informed review.
- Ground generation in documentation you trust. Retrieval-augmented generation can provide a model with selected manuals, API references, or internal standards. That can reduce guesses about versions and local conventions. It is not a truth machine: stale, incomplete, or misindexed documents can still lead to wrong answers. Keep the source set current and show reviewers which documents informed the suggestion. NIST’s Generative Artificial Intelligence Profile discusses risk management for generative AI systems.
- Measure what the checks catch. Track rejected packages, unsupported imports, security findings, and AI-assisted changes that needed correction. Review those numbers by language, repository, and type of task where possible. Do not turn the metric into a contest to make the number fall; that can encourage teams to hide problems. Use it to find weak checks, improve prompts, and decide where human review adds the most value.
In my experience, the best guardrails are boring and automatic. They run every time, not only when a reviewer happens to remember a warning from last month. That is the whole point: keep attention for decisions that need judgment, and let the pipeline reject claims it can verify cheaply.

AI Package Hallucinations vs. Traditional Typosquatting
Slopsquatting resembles typosquatting, but the initial mistake is different. Traditional typosquatting depends on a developer mistyping a known package name or choosing a confusing look-alike. Slopsquatting targets a name a model invented and then repeated. Both can end with an unsafe dependency in a project, so the same registry and review controls help with each.
| Comparison | AI package hallucination and slopsquatting | Traditional typosquatting |
|---|
| How the risky name appears | A model recommends a plausible package name that may not exist. | A developer mistypes or selects a look-alike for a real package. |
| Attacker’s opening | Register a hallucinated name that models tend to repeat. | Register a name close to a popular package or a common typo. |
| Why it may escape notice | The suggestion fits the code and arrives with confident explanation. | The typo may be small and easy to overlook in a command or import. |
| Repeat pattern | Researchers reported that fabricated names can recur across model sessions. | Risk often depends on repeated human typing mistakes or copied instructions. |
| Useful controls | Registry verification, approved dependencies, lockfile review, and package provenance checks. | Exact-name review, registry verification, approved dependencies, and lockfile review. |
The research figure above describes a particular test set; it should not be read as a universal rate for every model or team. The practical lesson is simpler: an unusual dependency name deserves verification before installation, whether a human or an assistant suggested it. Do not confuse a familiar naming style with proof of a real, safe package.
Common Mistakes to Avoid
Treating a successful build as proof of safety. A package can install and compile while carrying harmful behavior. A login flow can pass a basic test while remaining open to phishing or account takeover. Build success answers a narrow question: did this code pass these checks? It does not answer whether the design is sound.
Checking only whether the package exists. A registered package is not automatically trustworthy. Check ownership, release history, source repository, maintenance signals, and install behavior. For important projects, prefer known publishers and established packages. A registry lookup catches one class of hallucination; it does not perform a security review.
Assuming an AI answer is current. Models can reproduce old examples, deprecated APIs, and outdated security patterns. Ask which version a recommendation targets, then check the official documentation for that version. Authentication and cryptography change for good reasons. An answer that was acceptable years ago may be a poor choice now.
Using a broad prompt and accepting a broad policy. If you ask for a cloud policy that makes a service work, the assistant may grant more than the service needs. Give it the exact resource, actions, and constraints, then review each permission. The same rule applies to database roles, API scopes, and filesystem access. More access is not a harmless shortcut.
Relying on a human reviewer to catch everything. Review matters, but human attention is finite. I have seen code reviews catch a naming issue while overlooking an unpinned dependency simply because the change looked routine. Put repeatable checks in automation, then use human review for tradeoffs, threat models, and context the tools cannot see.
Believing retrieval makes output correct. Documentation retrieval can improve an answer, but the source may be stale or the model may misread it. Keep source documents versioned, test generated code, and preserve the same checks used for non-AI changes. The OWASP community lists misinformation as a generative-AI risk and recommends verification practices in its guidance on LLM misinformation. That is a useful warning, not a substitute for your own controls.
Frequently Asked Questions
Can AI coding assistants invent package names?
Yes. A model can produce a package name that follows familiar naming patterns even when no such package exists. Researchers testing 16 code-generating models reported that about one in five recommended dependencies in their study pointed to nonexistent packages, with more than 205,000 unique fabricated names in the test set. Those numbers describe the researchers’ experiment, not every AI tool or developer workflow. Check the exact name in the official registry before installing anything, then verify the package’s publisher and source.
What is slopsquatting?
Slopsquatting is an attack in which someone registers a package name that AI models tend to hallucinate. A developer may ask an assistant for code, accept the made-up dependency, and install the attacker’s real package by mistake. That package could run code during installation or become part of the application. The defense is straightforward, though it needs to be consistent: verify names, restrict sources where appropriate, review lockfiles, and examine package provenance before trusting a new dependency.
Are AI-generated authentication examples safe to use?
Not by default. A sample may omit account recovery, rate limits, secure session handling, or protection against phishing. It may also rely on a method that is weaker than current options for the account’s risk level. Review the full flow against current standards and product requirements; for high-value accounts, consider phishing-resistant passkeys or security keys. Test both normal use and failure cases, including lost devices and recovery. A polished code sample is a starting point, not a security design.

Does retrieval-augmented generation prevent hallucinations?
No. Retrieval can give a model approved documentation or internal standards to use, which may reduce unsupported guesses about APIs and versions. But the retrieved material can be old, incomplete, or irrelevant, and the model can still misinterpret it. Keep documents current, make sources visible, and verify generated claims against the actual reference. Continue using tests, dependency checks, and human review for high-risk code. Retrieval is a useful guardrail, not a guarantee.
Final thought: AI coding assistants can save time, but speed does not remove the duty to check what enters a system. A fabricated package, an old authentication pattern, or a cloud policy with excess rights can affect people who had no say in the code that serves them. Treating their safety as part of engineering is not red tape; it is respect for the dignity of the work and the people who depend on it.
I still like tools that help a developer get past a blank page. I do not like pretending that a fluent answer has done the hard parts of engineering. Verify the package. Check the version. Test the failure path. Limit access. Put repeatable checks in the pipeline, then give people time to review the choices that need judgment. That is how a team keeps the useful speed without handing its security decisions to autocomplete.