LLM Hallucinations in Practical Code Generation: Phenomena, Mechanism, and Mitigation

Ziyao Zhang, Yanlin Wang, Chong Wang, Jiachi Chen, Zibin Zheng

TL;DR

While Large Language Models (LLMs) are highly capable of generating standalone code snippets, they frequently stumble in real-world, repository-level development where complex contextual dependencies matter. This paper presents the first systematic study of LLM hallucinations within practical repository contexts, establishes a comprehensive taxonomy of these errors, and demonstrates that a lightweight Retrieval-Augmented Generation (RAG) approach can consistently improve code generation quality across multiple mainstream models.

What Problem Does This Paper Address?

Most existing evaluations of LLM code generation rely on benchmarks like HumanEval or DS-1000, which focus on standalone functions or isolated scripts. However, real-world software engineering is rarely standalone; over 70% of functions in open-source projects depend on local project contexts, such as user-defined APIs, unique data protocols, and specific environment configurations.

When forced to operate within these complex repositories, LLMs perform poorly. They often hallucinate independent code segments rather than utilizing the existing codebase. To bridge this gap, the authors investigate the specific phenomena, underlying mechanisms, and potential mitigations for LLM hallucinations in practical, repository-level code generation scenarios.

Methods

The authors executed a multi-step empirical study:

  1. Taxonomy Generation via Open Coding: They manually examined 1,380 code snippets generated by six mainstream LLMs (ChatGPT, CodeGen, PanGu-α, StarCoder2, DeepSeekCoder, and CodeLlama) using the CoderEval dataset. Through an iterative annotation process, they built a fine-grained taxonomy of code hallucinations.
  2. Root Cause Analysis: They analyzed the distribution of these hallucinations across different models to identify four primary drivers of hallucinatory behavior.
  3. RAG-Based Mitigation: To address these root causes, they developed a lightweight Retrieval-Augmented Generation (RAG) workflow. This system uses a sliding window to parse the local repository, converts code snippets into a sparse bag-of-words (BOW) representation, and applies the Jaccard index to retrieve and inject the top 10 most relevant context snippets directly into the LLM prompt.

Datasets

The study utilizes CoderEval, a benchmark designed to reflect pragmatic, repository-level development. It consists of 230 Python code generation tasks extracted from actual open-source repositories. Each task includes a natural language description, a ground-truth code snippet, test cases, and the broader project environment context.

Key Insights and Ideas

The authors established a clear taxonomy dividing code hallucinations into three primary categories:

Fig. 1. Taxonomy of Hallucinations in LLM-based Code Generation
  • Task Requirement Conflicts (43.53%): The most common issue, where the generated code fails to meet functional or non-functional requirements. For instance, models frequently overlook specific logic constraints described in docstrings (e.g., ignoring timezone handling).
  • Factual Knowledge Conflicts (31.91%): Occurs when the code violates external real-world facts, such as misusing third-party library APIs or inventing non-existent parameters (e.g., passing a year argument to datetime.timedelta()).
  • Project Context Conflicts (24.56%): Errors unique to repository-level tasks, where the model references undefined local methods, mismatched API versions, or non-existent file paths.
Fig. 2. Hallucination Distribution

The authors identified four root causes behind these failures:

  • Training Data Quality: LLMs inadvertently memorize insecure or flawed patterns present in their massive training corpora.
  • Intention Understanding Capacity: Models rely heavily on pattern recognition rather than a deep semantic understanding of user requirements, causing them to miss subtle edge cases.
  • Knowledge Acquisition Capacity: LLMs cannot naturally adapt to updates or domain-specific knowledge developed after their pre-training cutoff.
  • Repository-level Context Awareness: Token limits and the sheer volume of irrelevant information in a repository make it difficult for models to focus on the exact context needed.

Interestingly, models trained on a mix of diverse text and code (like DeepSeekCoder and CodeLlama) experienced fewer Task Requirement Conflicts than models trained predominantly on code alone (like CodeGen and StarCoder2), highlighting the importance of natural language comprehension in interpreting coding requirements.

Key Results

The lightweight RAG-based mitigation strategy consistently improved the functional correctness (measured via Pass@1) across all six evaluated models:

  • CodeLlama: Improved from 2.17% to 5.22% (+3.05%)
  • StarCoder2: Improved from 0.04% to 2.61% (+2.57%)
  • ChatGPT: Improved from 10.40% to 12.61% (+2.21%)
  • PanGu-α: Improved from 0.04% to 1.74% (+1.70%)
  • CodeGen: Improved from 1.30% to 2.61% (+1.31%)
  • DeepSeekCoder: Improved from 3.04% to 3.91% (+0.87%)

Qualitatively, providing local repository context successfully prevented models from inventing internal APIs (e.g., stopping ChatGPT from calling a non-existent self.items.popitem() method) and helped them select correct built-in string manipulation functions instead of breaking logic flow.

Limitations and Future Work

The study is primarily constrained by its focus on a single programming language (Python) and the relatively small scale of the CoderEval dataset (230 tasks). Additionally, the RAG mitigation method explored was intentionally preliminary and relied on a simple bag-of-words similarity metric restricted strictly to the local repository.

The authors note that future work should explore more sophisticated mitigation techniques, such as model fine-tuning, multi-agent developer frameworks, and expanding the RAG retrieval scope to include external documentation, online search engines, and StackOverflow discussions.

Summary updated

BibTeX
@inproceedings{zhang2024llm,
  author = {Ziyao Zhang and Yanlin Wang and Chong Wang and Jiachi Chen and Zibin Zheng},
  title = {{LLM Hallucinations in Practical Code Generation: Phenomena, Mechanism, and Mitigation}},
  booktitle = {Proc. ACM Softw. Eng},
  year = {2024},
}
Figure