Retrieval-Augmented Generation (RAG)
4.15.5kata 5 de 5

Grounding & Prompt Engineering

Instruir al LLM a usar solo el contexto

El modelo por defecto mezcla contexto recuperado con conocimiento de entrenamiento. Para RAG puro ('grounded' o 'retrieval-augmented'), debes instruir explícitamente: 'Responde SOLO usando el contexto abajo. Si la información no está en el contexto, di exactamente "Not found".' Sin esta instrucción, el modelo alucina.

La redacción del prompt importa. 'Answer the question' es vago. 'Answer using ONLY the context below. If the answer is not in the context, say "Not found". Do not use your training knowledge.' es claro. Incluso mejor: 'You are a document analyst. Your job is to answer questions about documents provided. You MUST cite the source document for every claim.'

El prompt puede incluir ejemplos (few-shot prompting) para reforzar el comportamiento. Ejemplo: 'Question: What is X? Context: [context]. Answer: [Correct answer is "X" because [fact from context].]' enseña al modelo a citar.

structure.txt
# === Basic grounding ===
def build_rag_prompt(context: str, question: str) -> str:
    return f'''You are a document analyst.
Answer the question using ONLY the context provided below.
If the answer is not in the context, respond with exactly: Not found.

Context:
{context}

Question: {question}
Answer:'''

# === With citation ===
def build_rag_prompt_with_citation(context: str, question: str) -> str:
    return f'''You are a document analyst.
Answer questions about documents, citing sources.

Instructions:
1. Answer using ONLY the context below.
2. For every claim, cite the source document or section.
3. If the answer is not in the context, say "Not found".

Example:
Q: What is the return policy?
A: The return policy allows 30 days from purchase (Handbook, Section 3.1). Returns must be in original condition (Handbook, Section 3.2).

Context:
{context}

Question: {question}
Answer:'''

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    prompt = f'Question: {query}\nContext: {context}\nAnswer:'

  2. 02

    # No fallback for missing information prompt = f'Context: {context}\nQ: {query}'

  3. 03

    # No grounding — allows model to use training knowledge prompt = f'Answer this question: {query}'