Выявление и уменьшение галлюцинаций
Галлюцинации — это уверенные, но ложные результаты LLM. Узнайте, почему они возникают, как их выявлять и какие практические методы помогают уменьшить их в рабочей среде.
«Выявление и уменьшение галлюцинаций» — бесплатный урок Prompt Engineering & LLM Optimization for Developers на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Prompt Engineering & LLM Optimization for Developers, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Prompt Engineering & LLM Optimization for Developers содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What is a Hallucination?
A hallucination is when an LLM produces text that is fluent and confident but factually wrong or unsupported by any source.
Because the output looks authoritative, hallucinations are dangerous in user-facing apps.
Why They Happen
LLMs predict the most likely next token, not the truth. With no grounding, they fill gaps with plausible-sounding inventions.
- Missing knowledge in training data
- Ambiguous or leading prompts
- Pressure to always answer
Types of Hallucination
Two broad categories:
- Factual: wrong dates, fake citations, invented APIs
- Faithfulness: answer contradicts the provided context (common in RAG)
Grounding with Context
The strongest defense is grounding: give the model trusted source text and instruct it to answer only from that text.
Answer ONLY using the context below.
If the answer is not in the context, say "I do not know".
Context:
{retrieved_docs}Forcing Citations
Ask the model to cite which passage supports each claim. Unsupported sentences become easy to spot and verify.
For each sentence, add a [doc_id] citation.
Do not make claims you cannot cite.Lowering Temperature
Higher temperature increases creativity — and invention. For factual tasks, set a low temperature so the model stays close to high-probability, well-grounded tokens.
const res = await client.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0,
messages
});Self-Consistency Checks
Generate the answer several times. If the model gives different facts each run, the claim is likely a hallucination. Agreement is a weak but useful signal of reliability.
LLM-as-a-Judge Verification
Use a second model call to check whether the answer is supported by the context. The judge returns a faithfulness verdict you can act on.
Does the ANSWER follow only from the CONTEXT?
Reply: SUPPORTED, PARTIAL, or UNSUPPORTED.Programmatic Validation
When outputs are structured, validate them. A cited URL should resolve, a quoted number should match the source, a JSON field should match a schema.
function validateCitation(cit, docs) {
return docs.some(d => d.id === cit.doc_id);
}Letting the Model Abstain
Give the model permission to say I do not know. Removing the pressure to always answer measurably reduces fabricated content.
Human Review for High Stakes
For medical, legal, or financial outputs, route low-confidence or uncited answers to a human before showing them to users. Automation plus oversight beats either alone.
Quick Check
Test your understanding.
Recap
You learned to fight hallucinations: ground answers in trusted context, force citations, lower temperature, use self-consistency and LLM-as-a-judge checks, validate outputs programmatically, allow abstention, and add human review for high-stakes cases.
Часто задаваемые вопросы
Урок «Выявление и уменьшение галлюцинаций» бесплатный?
Да — полный текст урока «Выявление и уменьшение галлюцинаций» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Prompt Engineering & LLM Optimization for Developers, подпишись на CoddyKit PRO. Курс Prompt Engineering & LLM Optimization for Developers содержит 4 уроков всего.
Чему я научусь в уроке «Выявление и уменьшение галлюцинаций»?
Галлюцинации — это уверенные, но ложные результаты LLM. Узнайте, почему они возникают, как их выявлять и какие практические методы помогают уменьшить их в рабочей среде. Ты практикуешь Prompt Engineering & LLM Optimization for Developers с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Prompt Engineering & LLM Optimization for Developers?
Предыдущий опыт не требуется. Prompt Engineering & LLM Optimization for Developers на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Выявление и уменьшение галлюцинаций»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Prompt Engineering & LLM Optimization for Developers?
Да. Каждый урок Prompt Engineering & LLM Optimization for Developers включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Метрики оценки и тестовые наборы для LLM
- Системы обратной связи с участием человека
- Атаки с внедрением промптов и рекомендации по безопасности
- Выявление и уменьшение галлюцинаций