Retrieval-Augmented Generation (RAG)
4.15.3kata 3 de 5

Hallucination Mitigation

Técnicas para prevenir respuestas fuera del contexto

Alucinación en RAG: el modelo mezcla información de su training data con el contexto recuperado, inventando hechos no presentes en el corpus. Ejemplo: contexto dice 'Device supports 2.4GHz' pero el modelo responde 'Device supports 2.4GHz and 5GHz WiFi'. Las 5GHz vienen del training data, no del documento.

Técnicas de mitigación: (1) Prompt explícito: 'Answer using ONLY the context below. If not in context, say "Not found".'. (2) Temperature = 0.0 (output determinístico, menos creatividad). (3) max_tokens bajo para forzar respuesta concisa (evita que el modelo interpole). (4) Penalizar tokens fuera del contexto con token biases (OpenAI API).

Test de hallucination: toma queries cuya respuesta CLARAMENTE no está en el contexto y verifica que el modelo devuelve 'Not found'. Ejemplo: si el contexto es sobre versión 1.0 de un producto y preguntas 'What is the feature list for version 2.0?', el modelo debe decir 'Not found', no inventar features de v2.0.

structure.txt
# === Anti-hallucination prompt ===
GROUNDED_PROMPT = '''You are a document analyst.
Your task is to answer questions about the provided documents ONLY.
Follow these rules strictly:
1. Read the context below carefully.
2. Answer ONLY using information from the context.
3. If the answer is not in the context, respond with exactly: "Not found in provided documents."
4. Do NOT use your training knowledge.
5. Do NOT infer or speculate.

Context:
{context}

Question: {question}
Answer:'''

# === Low temperature for consistency ===
response = llm.complete(
    prompt=GROUNDED_PROMPT.format(context=context, question=query),
    temperature=0.0,  # deterministic, no creativity
    max_tokens=256,   # short, focused answer
)

# === Test for hallucination ===
def test_hallucination_resistance():
    out_of_scope_query = 'What are the features of version 2.0?'  # not in context
    context_v1_only = 'Product version 1.0: feature A, feature B'
    response = rag_query(out_of_scope_query, context_v1_only)
    assert 'Not found' in response, f'Hallucinated: {response}'

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # Default temperature allows hallucinations response = llm.complete( prompt=f'Answer: {query}\nContext: {context}', temperature=0.7 # creative

  2. 02

    # No fallback for out-of-scope questions if 'version 2.0' in query and 'version 1.0' in context: # context is about v1, query asks about v2 # But no check — model will hallucinate v2 features

  3. 03

    # Long max_tokens encourages elaboration = hallucination response = llm.complete( prompt=GROUNDED_PROMPT.format(...), max_tokens=2000 # encourages long, made-up answers