Engineering Solutions for Detecting and Suppressing LLM Hallucinations

    This article explores why large language models hallucinate and how engineering teams can control the risk. It explains the technical causes behind confident but incorrect outputs, classifies hallucinations into four types with risk levels, and presents a five-layer defense strategy covering retrieval augmentation, schema validation, dual-channel consistency checks, prompt design with explicit fallback paths, and evaluation with monitoring. Readers will find practical implementation guidance, reusable prompt and code patterns, and recommendations for managing high-risk scenarios through controllable failure rather than zero hallucination.

    1. It Started with a Follow-Up on an Acronym

    In a public test, a user asked a large language model for the full meaning of a four-letter acronym. The model not only returned an incorrect company name but also “confidently” added that the acronym is sometimes written in another form in certain contexts. Its explanation had nothing to do with the question. What makes such answers dangerous is not that they are wrong, but that they sound certain and are well structured, reading like authoritative material.

    In the same test round, the user asked for private information the model could not possibly know (a specific date) and explicitly stated in the prompt, “If you know it, answer only with the date and month.” This gave the model a graceful way to decline. The result: one model produced three different incorrect guesses in a row, another produced two, and only after enabling deep thinking mode and spending about a minute and a half searching did one model finally admit, “I don’t know.”

    Both observations point to the same engineering problem: models lack a stable ability to say “I don’t know.” This article does not discuss any specific product. It treats the issue as a general class of technical defect to be governed.

    2. Technical Causes: Not Lying, but Probabilistic Completion

    To govern hallucinations, first understand why they are inevitable.

    1. The training objective is the probability distribution of the next token, not fact-checking. Models optimize for fluency and likelihood. Factual correctness is only a byproduct of statistical patterns in the training corpus. When a question falls into a sparse region of the corpus, the model still outputs the highest-probability string.
    2. Knowledge boundaries are invisible. Model parameters contain no explicit marker for whether a piece of knowledge is present. The model cannot determine before generation whether it has the answer.
    3. Alignment training rewards being “helpful” and penalizes being “empty.” Overemphasizing that an answer must be given systematically suppresses the probability of “I don’t know,” producing the side effect of a refusal rate that is too low.
    4. Decoding strategies amplify confidence. Low temperature and greedy decoding make high-probability wrong answers reproduce more consistently, so errors appear “consistent and credible.”
    5. Context contamination. False premises and fabricated citations in the prompt are treated as trustworthy material and used for further reasoning, causing cascading errors.

    3. Four Typical Forms of Hallucination and Risk Levels

    Form Symptoms Typical Scenarios Risk Level
    Factual hallucination Wrong names, acronyms, dates, or numbers Document retrieval, customer support Q&A High
    Citation hallucination Fabricated clauses, papers, or APIs Legal, medical, R&D documentation Very High
    Reasoning hallucination Correct premises but a broken chain Data analysis, code review Medium-High
    Instruction hallucination Ignoring the “say you don’t know” constraint Automated pipelines High

    The principle for risk classification is simple: the more likely the output is consumed as fact by a downstream system, the higher the risk. A wrong piece of copy may only be embarrassing; a wrong API parameter can directly cause a production incident.

    4. Engineering Suppression: Five Layers of Defense

    Layer 1: Retrieval Augmentation, Replacing “Memory” with Verifiable Citations

    Place external knowledge in a retrieval pipeline so the model does a “reading comprehension” task instead of a “closed-book exam.” Connecting retrieval is not enough. The generation behavior must be constrained:

    1. [System Constraint]
    2. 1. Answer only based on the content in <context>;
    3. 2. Append the source number [1][2] after each conclusion;
    4. 3. If <context> does not contain the answer, output only: INSUFFICIENT_EVIDENCE;
    5. 4. Do not complete entity names, numbers, or dates outside the context.

    In practice, rerank and threshold-filter the retrieved results. Discard fragments whose similarity falls below the threshold to prevent “weak evidence” from prompting the model to fill in gaps on its own.

    Layer 2: Structured Output and Schema Validation

    Turn free text into a constrained structure so errors surface at the parsing stage:

    1. import json
    2. from jsonschema import validate
    3. SCHEMA = {
    4. "type": "object",
    5. "required": ["answer", "confidence", "sources"],
    6. "properties": {
    7. "answer": {"type": ["string", "null"]},
    8. "confidence": {"type": "number", "minimum": 0, "maximum": 1},
    9. "sources": {"type": "array", "items": {"type": "string"}},
    10. },
    11. }
    12. def parse(raw: str):
    13. data = json.loads(raw)
    14. validate(data, SCHEMA)
    15. if data["confidence"] < 0.6 or not data["sources"]:
    16. return {"answer": None, "reason": "low_confidence"}
    17. return data

    The key point: allow answer to be null, giving the model a legitimate way to abstain at the protocol level rather than begging it in natural language to admit ignorance.

    Layer 3: Self-Check and Dual-Channel Consistency

    Solve the same question through two paths: one generates directly, the other retrieves first and then generates. When the conclusions conflict, do not vote and do not compromise. Downgrade directly to “requires human confirmation.” For high-risk fields (numbers, dates, IDs), add extra regex and business-rule validation, for example, dates must fall within a valid range and IDs must satisfy check-digit rules.

    Layer 4: Designing a “Retreat Path” at the Prompt Level

    The most valuable takeaway from the original test is explicitly stating that not knowing is allowed. A reusable prompt skeleton:

    1. - If evidence is insufficient, answer "UNKNOWN"; do not guess;
    2. - Do not use vague phrasing such as "possibly" or "presumably" to package guesses;
    3. - Self-check before output: can each entity be located in the given material?

    Also avoid planting unverified premises in the prompt to prevent context contamination.

    Layer 5: Evaluation, Monitoring, and a Closed Loop

    • Build a hallucination evaluation set: cover four categories (acronyms, dates, numbers, citations), with metrics including refusal accuracy, error rate, and citation verifiability.
    • Set up production monitoring and alerts: configure threshold alerts for drift in the confidence distribution, a sudden drop in refusal rate, and a rise in the missing-citation rate.
    • Human review loop: route high-risk outputs to a review queue, and feed review conclusions back as new evaluation samples.
    • Observability trio: a logging service records full prompts and responses, monitoring and alerting track quality metrics, a message queue handles asynchronous review tasks, and object storage archives sample sets.

    5. Implementation Advice for High-Risk Scenarios

    1. Tiered governance: tag scenarios by the severity of error consequences. High-risk scenarios must enable the triple constraint of retrieval, structured output, and human review.
    2. Do not pursue zero hallucination; pursue controllable failure: the goal is to have errors “intercepted,” not “never produced.”
    3. Treat refusal as a first-class citizen: product copy and interaction design must leave room for “I’m not sure,” otherwise the model is forced to fabricate.
    4. Account for the cost of trading money for safety: deep reasoning and multi-round self-checks bring latency and compute overhead. Enable them dynamically by scenario, and route low-risk requests through a lightweight pipeline.
    5. When implementing on Baidu AI Cloud, you can directly combine general capability categories: object storage holds evaluation samples, a message queue decouples the review workflow, a container platform hosts inference services, and logging plus monitoring and alerting form a quality dashboard. The closed loop can be completed without relying on any proprietary interface.

    6. Conclusion

    “Returning a wrong full name and adding an even more absurd acronym” and “guessing a date wrong three times in a row” are two manifestations of the same defect: the model was not trained to reliably say “I don’t know.” The engineering answer is not to switch to a stronger model, but to combine verifiable evidence, structured protocols, confidence thresholds, self-check mechanisms, and human review into a single line of defense, making uncertainty visible, interceptable, and traceable within the system.