Hallucination
Hallucination
A phenomenon in which an LLM generates content that is not factual. Mitigated with RAG and verification systems. A core challenge for AI trustworthiness.
Hallucination
A phenomenon in which an LLM generates content that is not factual. Mitigated with RAG and verification systems. A core challenge for AI trustworthiness.
Hallucination is a phenomenon in which a large language model (LLM) confidently generates information that is not factual as if it were true. Typical examples include citing papers that do not exist, fabricated historical facts, and incorrect legal provisions. It has not been completely resolved even in the latest models such as GPT-4, Claude, and Gemini, and it is one of the biggest challenges to AI reliability and safety.
The root cause of hallucination lies in how LLMs work. LLMs learn statistical patterns from training data and predict "the token most likely to come next." In this process, they generate plausible-sounding text without fact verification. Errors in the training data, requests for information not in the training data, and incorrect combinations of conflicting information cause hallucinations. The problem is especially aggravated when a model is trained to generate an answer rather than say "I don't know."
As of 2024-2025, a variety of techniques for mitigating hallucination have advanced. RAG (Retrieval-Augmented Generation) searches external knowledge sources to provide grounding for responses. Self-consistency generates multiple times and then checks the degree of agreement. Citation generation makes the model state its sources, which makes verification easier. Some models, such as Perplexity AI, automatically attach source links to answers, and others, such as Claude, are trained to state explicitly when they are uncertain.
In practice, managing hallucination is central to AI system design. In high-risk domains such as healthcare, law, and finance, human review (Human-in-the-loop) is essential. It is advisable to apply RAG to tasks where factual accuracy matters and to assign confidence scores to outputs. It is also recommended to design prompts so that the model can say "I'm not sure," and to include hallucination detection tools (Vectara, Galileo) in the pipeline.
This is an example implementing hallucination detection and mitigation techniques.
from openai import OpenAI
from anthropic import Anthropic
import json
from dataclasses import dataclass
from typing import Optional
import re
client = OpenAI()
anthropic = Anthropic()
@dataclass
class HallucinationCheckResult:
"""할루시네이션 검사 결과"""
is_grounded: bool # 근거가 있는지
confidence: float # 신뢰도 (0-1)
issues: list[str] # 발견된 문제점
citations: list[str] # 인용된 출처
# 1. 자기 일관성 검사 (Self-Consistency)
def check_self_consistency(prompt: str, n_samples: int = 5) -> dict:
"""동일 질문에 여러 번 답변 생성 후 일관성 확인"""
responses = []
for _ in range(n_samples):
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.7 # 다양성을 위해 temperature 사용
)
responses.append(response.choices[0].message.content)
# 일관성 분석
analysis = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
{
"role": "system",
"content": """다음 여러 응답들의 일관성을 분석하세요.
JSON 형식으로 응답: {
"consistency_score": 0.0-1.0,
"consistent_facts": ["일관된 사실들"],
"inconsistent_facts": ["불일치하는 내용들"],
"recommended_answer": "가장 신뢰할 수 있는 답변"
}"""
},
{
"role": "user",
"content": f"원본 질문: {prompt}\n\n응답들:\n" +
"\n---\n".join(f"응답 {i+1}: {r}" for i, r in enumerate(responses))
}
],
response_format={"type": "json_object"}
)
return json.loads(analysis.choices[0].message.content)
# 2. RAG 기반 근거 검증
def verify_with_rag(
claim: str,
context_documents: list[str]
) -> HallucinationCheckResult:
"""RAG로 검색한 문서와 주장 대조"""
context = "\n\n".join(f"[문서 {i+1}] {doc}" for i, doc in enumerate(context_documents))
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
{
"role": "system",
"content": """당신은 사실 검증 전문가입니다.
주어진 컨텍스트를 기반으로 주장의 정확성을 검증하세요.
JSON 형식으로 응답:
{
"is_grounded": true/false,
"confidence": 0.0-1.0,
"supporting_evidence": ["근거가 되는 문서 내용"],
"contradicting_evidence": ["반박되는 내용"],
"unverifiable_claims": ["검증 불가능한 주장"],
"verdict": "SUPPORTED/REFUTED/NOT_ENOUGH_INFO"
}"""
},
{
"role": "user",
"content": f"검증할 주장:\n{claim}\n\n참고 문서:\n{context}"
}
],
response_format={"type": "json_object"}
)
result = json.loads(response.choices[0].message.content)
return HallucinationCheckResult(
is_grounded=result["is_grounded"],
confidence=result["confidence"],
issues=result.get("contradicting_evidence", []) + result.get("unverifiable_claims", []),
citations=result.get("supporting_evidence", [])
)
# 3. 할루시네이션 방지 프롬프트
def generate_with_uncertainty(query: str) -> dict:
"""불확실성을 표현하도록 유도하는 생성"""
response = anthropic.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2000,
system="""당신은 정확성을 최우선으로 하는 AI 어시스턴트입니다.
다음 규칙을 반드시 따르세요:
1. 확실하지 않은 정보는 "~로 알고 있습니다", "~일 수 있습니다"로 표현
2. 모르는 것은 솔직히 "이 정보는 확인이 필요합니다"라고 말씀
3. 숫자, 날짜, 인용은 특히 신중하게 - 불확실하면 생략
4. 가능하면 검증 가능한 출처 언급
5. 추측과 사실을 명확히 구분
응답 마지막에 [신뢰도: 높음/중간/낮음]을 표시하세요.""",
messages=[{"role": "user", "content": query}]
)
text = response.content[0].text
# 신뢰도 추출
confidence_match = re.search(r'\[신뢰도:\s*(높음|중간|낮음)\]', text)
confidence = confidence_match.group(1) if confidence_match else "중간"
return {
"response": text,
"confidence": confidence,
"has_uncertainty_markers": any(
marker in text for marker in
["~로 알고 있습니다", "~일 수 있습니다", "확인이 필요", "불확실"]
)
}
# 4. 인용 기반 응답 생성
def generate_with_citations(
query: str,
sources: list[dict] # [{"title": "...", "content": "...", "url": "..."}]
) -> dict:
"""출처를 인용하는 응답 생성"""
sources_text = "\n\n".join(
f"[출처 {i+1}] {s['title']}\n{s['content']}"
for i, s in enumerate(sources)
)
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
{
"role": "system",
"content": """주어진 출처만을 사용해 질문에 답변하세요.
규칙:
1. 각 주장 뒤에 [출처 N] 형식으로 인용
2. 출처에 없는 정보는 "해당 출처에서 확인되지 않음"으로 표시
3. 여러 출처를 종합할 때 [출처 1, 3] 형식 사용
4. 출처 간 정보가 다르면 양쪽 모두 언급"""
},
{
"role": "user",
"content": f"질문: {query}\n\n{sources_text}"
}
]
)
answer = response.choices[0].message.content
# 인용 추출
citations = re.findall(r'\[출처 (\d+(?:,\s*\d+)*)\]', answer)
return {
"answer": answer,
"citations_used": list(set(
int(c) for citation in citations
for c in re.findall(r'\d+', citation)
)),
"all_sources_cited": len(citations) > 0
}
# 사용 예시
if __name__ == "__main__":
# 자기 일관성 검사
print("=== 자기 일관성 검사 ===")
result = check_self_consistency("대한민국의 수도는 언제 서울로 정해졌나요?")
print(f"일관성 점수: {result['consistency_score']}")
# 불확실성 표현 생성
print("\n=== 불확실성 표현 생성 ===")
response = generate_with_uncertainty("GPT-5는 언제 출시되나요?")
print(f"신뢰도: {response['confidence']}")
print(f"불확실성 표현 포함: {response['has_uncertainty_markers']}")
| Technique | Effects | Cost | Difficulty of Adoption |
|---|---|---|---|
| RAG (Retrieval-Augmented Generation) | High | Medium | Medium |
| Self-Consistency | Medium | High (N× calls) | Easy |
| Forced Citation/Sourcing | Medium | Low | Easy |
| Human-in-the-loop | Very high | Very high | Difficult |
| Fine-tuning (RLHF) | High | Very high | Very Difficult |
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Even the latest models hallucinate. Always verify numbers, dates, citations, and legal/medical information separately. Do not be fooled by the model's confident tone.
RAG can also retrieve the wrong documents or misinterpret their contents. You need a pipeline that checks both retrieval quality and answer-to-document consistency.
Combine RAG + forced citation + uncertainty expression + detection model + selective human review. Using several techniques together can reduce hallucination more effectively than any single technique.