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

Ziyao Zhang, Chong Wang, Yanlin Wang, Ensheng Shi, Yuchi Ma, Wanjun Zhong, Jiachi Chen, Mingzhi Mao, Zibin Zheng

TL;DR

Large Language Models (LLMs) are revolutionizing code generation, but they often "hallucinate" – produce incorrect or nonsensical code, especially in complex, real-world scenarios. This paper systematically investigates these hallucinations, categorizing them, analyzing their root causes (like data quality and context awareness), and proposing a practical mitigation strategy using retrieval-augmented generation (RAG) that improves LLM performance.

What Problem Does This Paper Address?

Code generation using LLMs promises to boost developer productivity by automating code creation. While LLMs excel at generating standalone functions, they struggle with more realistic code generation tasks that involve understanding project-specific context, dependencies, and intricate requirements. These struggles manifest as "hallucinations" – code that is syntactically correct but functionally wrong, insecure, or simply doesn't meet the intended purpose. Existing research often focuses on simpler benchmarks, leaving a gap in understanding and addressing hallucinations in practical, repository-level code generation. This paper aims to bridge that gap by providing a taxonomy, analyzing causes, and proposing a mitigation.

Methods

The researchers employed a multi-pronged approach:

  • Manual Annotation and Taxonomy Development: They manually analyzed code generated by six mainstream LLMs on a dataset of practical coding tasks. Through an iterative open-coding process, they developed a taxonomy of LLM hallucinations, categorizing them into three main types (Task Requirement Conflicts, Factual Knowledge Conflicts, and Project Context Conflicts) with eight subcategories.
  • Root Cause Analysis: They investigated the underlying reasons for these hallucinations, identifying four key contributing factors: training data quality, the LLM's ability to understand user intentions, its knowledge acquisition capacity, and its awareness of the repository-level context.
  • RAG-based Mitigation: They proposed and evaluated a lightweight Retrieval-Augmented Generation (RAG) approach. This method involves constructing a retrieval library from the target code repository and using relevant code snippets as prompts to guide the LLM during generation.

Datasets

  • CoderEval: This dataset was used for evaluation. It comprises 230 Python code generation tasks extracted from real-world repositories, including natural language descriptions, ground-truth code, and test cases, along with project environment context.

Key Insights and Ideas

  • Hallucinations are Pervasive and Complex: The study reveals that hallucinations are not just minor glitches but significant issues that can lead to functional errors, security vulnerabilities, and increased maintenance burdens.
  • Context is King (and LLMs Struggle With It): The most prevalent type of hallucination, "Task Requirement Conflicts," highlights LLMs' difficulty in fully grasping and adhering to the specific functional and non-functional requirements of a task, especially when project-specific context is involved.
  • Root Causes are Multifaceted: Hallucinations aren't solely due to one factor. They stem from a combination of issues with the training data (quality, diversity), the LLM's inherent limitations in understanding intent and acquiring knowledge, and its struggle to incorporate repository-specific context.
  • RAG Offers a Practical Solution: The proposed RAG-based mitigation effectively improves LLM performance across various models, demonstrating that providing relevant contextual information can significantly reduce hallucinations.

Key Results

  • Hallucination Taxonomy: The paper establishes a taxonomy with three main categories and eight subtypes, providing a structured way to understand LLM code generation errors.
  • Distribution of Hallucinations: "Task Requirement Conflicts" were the most frequent hallucination type (43.53%), followed by "Factual Knowledge Conflicts" (31.91%) and "Project Context Conflicts" (24.56%).
  • Model Comparison: CodeGen and StarCoder2 showed a higher frequency of Task Requirement Conflicts, while DeepSeekCoder and CodeLlama had the lowest occurrence. PanGu-a exhibited the highest frequency of factual hallucinations.
  • RAG Mitigation Effectiveness: The RAG-based approach consistently improved the Pass@1 metric (a measure of functional correctness) for all six LLMs tested, with improvements ranging from 0.87% to 3.05%.

Limitations and Future Work

  • Generalizability: The study primarily focused on Python code. Future work could extend the taxonomy and analysis to other programming languages.
  • Dataset Scale: While the CoderEval dataset is representative, its size (230 tasks) could be expanded.
  • RAG Enhancement: The current RAG implementation is preliminary. Future work could explore integrating more comprehensive knowledge sources (e.g., online search, API docs), refining retrieval mechanisms, and developing multi-agent systems for iterative improvement.
  • Hallucination Identification: Developing more effective techniques to automatically identify and localize hallucinations remains an open challenge.

Summary updated

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