Skip to main content
Prompt Engineering Tutorial
CHAPTER 15 Beginner

Avoiding AI Hallucinations and Errors

Updated: May 14, 2026
25 min read

# CHAPTER 15

Avoiding AI Hallucinations and Errors

1. Introduction

The greatest threat to an AI developer is an AI that lies with confidence. Hallucinations—instances where an LLM invents fake facts, fake math, or fake code—can destroy the credibility of an application and cause massive real-world harm. In this chapter, we will learn how to engineer "guardrails" into our prompts to minimize ambiguity, force factual grounding, and drastically reduce the hallucination rate.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the root cause of AI Hallucinations.
  • Write prompts that force the AI to admit when it doesn't know an answer.
  • Implement prompt-based Fact-Checking constraints.
  • Utilize the "Provide Citations" technique.

3. Beginner-Friendly Explanation

Imagine taking a test in school. The teacher asks a question you didn't study for. If you leave it blank, you get a zero. Because you desperately want to pass, you write a completely fabricated, highly detailed essay hoping the teacher is fooled. An LLM works the same way. It is mathematically programmed to be "helpful." If you ask it a question it doesn't know, it feels a strong mathematical urge to provide an answer anyway. So, it guesses. Because it is so good at language, its guess sounds incredibly convincing. To stop this, you have to engineer a prompt that explicitly gives the AI "permission" to leave the test blank.

4. The Anti-Hallucination Clause

The simplest way to prevent hallucination is to hard-code an "opt-out" clause into your System Prompt.

Dangerous Prompt:

text
1
Answer the user's question about our company policy.

*(If the policy isn't provided, the AI will invent a fake policy).*

Safe Prompt (The Opt-Out Clause):

text
12
Answer the user's question about our company policy.
CONSTRAINT: If you do not know the answer, or if the answer is not explicitly stated in the provided text, you MUST reply EXACTLY with: "I'm sorry, I do not have that information." DO NOT guess. DO NOT invent facts.

5. Grounding with Context (RAG Basics)

Never rely on the AI's internal, pre-trained memory for facts. Always provide the facts in the prompt itself. This is the foundation of RAG (Retrieval-Augmented Generation).
text
12345
# CONTEXT
[Paste a verified Wikipedia article or company document here]

# TASK
Based STRICTLY on the Context provided above, answer the question.

6. Forcing Citations

If you provide a large document and ask for a summary, force the AI to prove its work.
text
123
Summarize the 10-page contract provided. 
For every claim you make in your summary, you MUST provide a direct quote from the contract in parentheses.
Example: The contract lasts 5 years ("Term: 5 Years").

This constraint prevents the AI from summarizing something that isn't actually in the text, because it is mathematically forced to find a matching quote.

7. Fact-Checking (The Self-Correction Prompt)

You can use an AI to fact-check an AI. This is called Self-Reflection Prompting.

Step 1: The AI generates an essay. Step 2: You pass the essay back into the AI with a new prompt:

text
12
Act as a ruthless Fact-Checker. Read the essay below. 
Identify any claims, statistics, or dates that might be hallucinated or incorrect. Output a list of potential errors.

8. Python Example: The Guardrail Loop

Developers build automated loops to catch hallucinations.
python
123456789101112
def generate_and_verify(question, document):
    # Step 1: Generate Answer
    prompt1 = f"Answer '{question}' based on '{document}'."
    draft_answer = call_llm(prompt1)
    
    # Step 2: Verify Answer
    prompt2 = f"Does this answer: '{draft_answer}' rely on ANY information NOT present in this document: '{document}'? Answer Yes or No."
    verification = call_llm(prompt2)
    
    if "Yes" in verification:
        return "Error: Hallucination detected. Answer rejected."
    return draft_answer

9. Mini Project

The Refusal Prompt: You are building a Medical AI Chatbot. Write a highly strict System Prompt that ensures the AI answers basic biology questions, but absolutely refuses to diagnose a user's symptoms or recommend medication. *(Answer Example: "Role: Biology Tutor. You may explain anatomical concepts. STRICT CONSTRAINT: If a user describes personal symptoms or asks for medical advice, you must immediately halt and reply: 'I am an AI, not a doctor. Please consult a licensed medical professional.' You are forbidden from diagnosing or recommending treatments.")*

10. Best Practices

  • Temperature Control: As discussed in previous chapters, if you are performing factual extraction or research, lower the API temperature to 0.0. This mathematically removes the AI's "creativity," significantly reducing the chance of hallucination.

11. Common Mistakes

  • Assuming High Quality Writing = Truth: The most dangerous hallucinations are the ones that sound the most professional. Never let the AI's flawless grammar trick you into believing its fabricated statistics. Always verify.

12. Exercises

  1. 1. Explain why giving an LLM an explicit "Opt-Out Clause" (e.g., "If you don't know, say 'I don't know'") drastically reduces hallucination rates.

13. MCQs with Answers

Question 1

What is an AI Hallucination?

Question 2

Which prompt constraint is most effective for ensuring an AI does not hallucinate facts when summarizing a long document?

14. Interview Questions

  • Q: Describe the mechanical cause of an LLM hallucination. What specific Prompt Engineering constraints would you implement to prevent an AI customer service bot from inventing fake refund policies?
  • Q: How do you use "Self-Reflection" or a secondary verification prompt to automatically detect and filter out hallucinations in an enterprise pipeline?

15. FAQs

Q: Will AI companies ever completely fix hallucinations? A: Likely not 100%. Hallucinations are a feature, not a bug, of generative models. The exact same mathematical "randomness" that allows an AI to invent a beautiful, original poem is the mechanism that causes it to invent a fake court case. You cannot have generation without the risk of fabrication.

16. Summary

In Chapter 15, we learned how to cage the beast. Hallucinations are the natural byproduct of a predictive language model. To build safe applications, prompt engineers must aggressively implement guardrails. By providing explicit context, forcing citations, writing strict Opt-Out clauses, and utilizing Self-Reflection verification loops, we force the AI to remain grounded in reality, transforming it from a creative liar into a reliable analytical tool.

17. Next Chapter Recommendation

You know how to write the perfect, safe prompt. Now, let's automate it. Proceed to Chapter 16: Prompt Engineering Workflows and Automation.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·