Saltar al contenido principal

Capítulo 2: Tipos de Prompts (Zero-shot, Few-shot)

🎯 Objetivos de Aprendizaje​

Después de completar este capítulo, usted podrá:

  • Definir y aplicar zero-shot prompting
  • Definir y aplicar few-shot prompting
  • Determinar cuándo utilizar cada enfoque
  • Crear ejemplos efectivos para few-shot learning

📚 Introducción​

Una de las decisiones más importantes en la ingeniería de prompts es si proporcionar ejemplos o no. Este capítulo explora los dos enfoques fundamentales: zero-shot (sin ejemplos) y few-shot (con ejemplos) prompting.

Comprendiendo la Terminología​

Antes de comenzar, aclaremos estos términos tomados del aprendizaje automático:

TérminoSignificado en IASignificado en Prompting
Zero-shotEl modelo realiza la tarea sin entrenamiento específicoPrompt sin ejemplos
One-shotEl modelo aprende de un ejemploPrompt con un ejemplo
Few-shotEl modelo aprende de unos pocos ejemplosPrompt con 2-5+ ejemplos

Zero-Shot Prompting​

Zero-shot prompting significa pedirle a la IA que realice una tarea sin proporcionar ningún ejemplo.

Cómo Funciona​

┌─────────────────────────────────────────────────────────────┐
│ ZERO-SHOT PROMPTING │
├─────────────────────────────────────────────────────────────┤
│ │
│ USER: "Translate 'Hello, how are you?' to French" │
│ │
│ AI relies on: │
│ • Pre-trained knowledge │
│ • Understanding of task from instruction │
│ • No specific examples provided │
│ │
│ AI: "Bonjour, comment allez-vous ?" │
│ │
└─────────────────────────────────────────────────────────────┘

Ejemplos de Zero-Shot​

Clasificación simple:

Classify the sentiment of this review as positive,
negative, or neutral:

"The product arrived on time but the quality was
disappointing. Won't buy again."

Sentiment:

Generación de texto:

Write a professional email declining a job offer
politely while leaving the door open for future
opportunities.

Extracción de información:

Extract the date, time, and location from this text:

"The conference will be held on March 15, 2024,
at 9 AM in the Grand Ballroom of the Hilton Hotel."

Cuándo Usar Zero-Shot​

✅ Utilice zero-shot cuando:

  • La tarea es sencilla y bien definida
  • Es probable que la IA tenga capacidades preentrenadas sólidas para la tarea
  • Desea resultados rápidos sin crear ejemplos
  • El formato/estilo que desea es estándar

❌ Evite zero-shot cuando:

  • La tarea requiere un formato específico
  • Necesita consistencia en muchos resultados
  • La tarea es inusual o específica de un dominio
  • Los resultados iniciales de zero-shot son inconsistentes

Few-Shot Prompting​

Few-shot prompting proporciona ejemplos que demuestran el patrón de entrada-salida deseado.

Cómo Funciona​

┌─────────────────────────────────────────────────────────────┐
│ FEW-SHOT PROMPTING │
├─────────────────────────────────────────────────────────────┤
│ │
│ EXAMPLES PROVIDED: │
│ ┌─────────────────────────────────────────┐ │
│ │ Example 1: Input → Output │ │
│ │ Example 2: Input → Output │ │
│ │ Example 3: Input → Output │ │
│ └─────────────────────────────────────────┘ │
│ │
│ NEW INPUT: [Your actual task] │
│ │
│ AI learns the pattern from examples and applies it │
│ │
└─────────────────────────────────────────────────────────────┘

Ejemplo Few-Shot: Clasificación de Sentimiento​

Classify the sentiment of movie reviews.

Review: "This movie was absolutely fantastic! Best film I've seen this year."
Sentiment: Positive

Review: "Terrible acting, boring plot. Complete waste of time."
Sentiment: Negative

Review: "It was okay. Some good parts, some not so good."
Sentiment: Neutral

Review: "The special effects were amazing but the story was predictable."
Sentiment:

Ejemplo Few-Shot: Extracción de Datos​

Extract product information from descriptions.

Description: "Apple MacBook Pro 14-inch, M3 chip, 16GB RAM, 512GB SSD, Space Gray - $1,999"
Product: MacBook Pro 14-inch
Brand: Apple
Specs: M3 chip, 16GB RAM, 512GB SSD
Color: Space Gray
Price: $1,999

Description: "Samsung Galaxy S24 Ultra, 256GB, Titanium Black, Unlocked - $1,299.99"
Product: Galaxy S24 Ultra
Brand: Samsung
Specs: 256GB, Unlocked
Color: Titanium Black
Price: $1,299.99

Description: "Sony WH-1000XM5 Wireless Noise Canceling Headphones, Silver - $349"
Product:
Brand:
Specs:
Color:
Price:

Ejemplo Few-Shot: Formato Personalizado​

Convert meeting notes to action items format.

Notes: "John will update the website by Friday. Sarah needs to review the budget proposal. Team should schedule a follow-up meeting next week."

Action Items:
• [ ] John: Update website (Due: Friday)
• [ ] Sarah: Review budget proposal
• [ ] Team: Schedule follow-up meeting (Due: Next week)

---

Notes: "Marketing to prepare Q2 campaign by March 1st. Dev team should fix the login bug ASAP. Lisa will coordinate with the vendor about pricing."

Action Items:
• [ ] Marketing: Prepare Q2 campaign (Due: March 1st)
• [ ] Dev team: Fix login bug (Priority: ASAP)
• [ ] Lisa: Coordinate with vendor about pricing

---

Notes: "Tom needs to finish the report. The design team will create new mockups. We should update clients about the delay."

Action Items:

Comparación: Zero-Shot vs Few-Shot​

AspectoZero-ShotFew-Shot
Ejemplos necesariosNinguno2-5+
Tiempo de preparaciónMínimoMás esfuerzo
ConsistenciaVariableMayor
Uso de tokensMenorMayor (los ejemplos consumen tokens)
Mejor paraTareas estándarFormatos personalizados, casos límite
Curva de aprendizajeMenorRequiere buena selección de ejemplos

Comparación Visual​

ZERO-SHOT:
┌─────────────────────────────────────┐
│ Task: Classify sentiment │
│ │
│ Input: "Great product!" │
│ │
│ → AI uses general knowledge │
│ │
│ Output: Positive │
└─────────────────────────────────────┘

FEW-SHOT:
┌─────────────────────────────────────┐
│ Task: Classify sentiment │
│ │
│ Example 1: "Love it!" → Positive │
│ Example 2: "Hate it!" → Negative │
│ Example 3: "It's fine" → Neutral │
│ │
│ Input: "Great product!" │
│ │
│ → AI learns pattern from examples │
│ │
│ Output: Positive │
└─────────────────────────────────────┘

Mejores Prácticas para Ejemplos Few-Shot​

1. Diversidad en los Ejemplos​

Incluya ejemplos que cubran diferentes escenarios:

✓ BUENO: Ejemplos diversos
- Reseña positiva (corta)
- Reseña negativa (detallada)
- Reseña neutral (sentimientos mixtos)

✗ MALO: Ejemplos homogéneos
- Reseña positiva
- Otra reseña positiva
- Otra reseña positiva más

2. Formato Consistente​

Mantenga la misma estructura en todos los ejemplos:

✓ BUENO: Formato consistente
Input: "text" → Category: [result]
Input: "text" → Category: [result]
Input: "text" → Category: [result]

✗ MALO: Formato inconsistente
Input: "text" → Category: [result]
"text" is: [result]
[result] for "text"

3. Ejemplos Representativos​

Elija ejemplos que representen casos de uso reales:

✓ BUENO: Realista
"The delivery was late but the product quality is excellent" → Mixed

✗ MALO: Artificial
"Product good. Happy. Buy again." → Positive

4. Delimitadores Claros​

Separe los ejemplos de manera clara:

✓ BUENO: Separación clara
Example 1:
Input: [text]
Output: [result]

---

Example 2:
Input: [text]
Output: [result]

---

Now process:
Input: [new text]
Output:

¿Cuántos Ejemplos?​

NúmeroNombreCaso de Uso
0Zero-shotTareas estándar y bien definidas
1One-shotDemostración de patrón simple
2-3Few-shotLo más común para tareas personalizadas
4-5Few-shotTareas complejas o matizadas
6+Many-shotPatrones altamente específicos
Token Economics

Más ejemplos = más tokens = mayor costo. Encuentre el número mínimo de ejemplos que logre resultados consistentes.

Avanzado: Few-Shot con Chain-of-Thought​

Combine few-shot con explicaciones de razonamiento:

Solve these word problems.

Problem: "A store has 45 apples. They sell 12 and receive a shipment of 30. How many apples do they have?"
Thinking: Start with 45, subtract 12 sold (45-12=33), add 30 received (33+30=63)
Answer: 63 apples

Problem: "If a train travels at 60 mph for 2.5 hours, how far does it go?"
Thinking: Distance = Speed × Time, so 60 mph × 2.5 hours = 150 miles
Answer: 150 miles

Problem: "A recipe needs 3 cups of flour for 12 cookies. How much flour for 20 cookies?"
Thinking:
Answer:

Ejercicio Práctico​

Ejercicio: Convertir Zero-Shot a Few-Shot​

Este prompt zero-shot da resultados inconsistentes:

Convert these informal messages to professional emails.

Message: "hey can u send me the report asap thx"

Su tarea: Cree una versión few-shot con 2-3 ejemplos que asegure un formato consistente.

Ver solución
Convert informal messages to professional emails.

Message: "hey can u send me the report asap thx"
Professional Email:
Subject: Report Request
Dear [Name],
I hope this message finds you well. Could you please
send me the report at your earliest convenience?
Thank you for your assistance.
Best regards,
[Your name]

---

Message: "yo meeting 2morrow is cancelled btw"
Professional Email:
Subject: Meeting Cancellation Notice
Dear Team,
I wanted to inform you that tomorrow's meeting has
been cancelled. I apologize for any inconvenience.
We will reschedule and notify you of the new date.
Best regards,
[Your name]

---

Message: "can someone fix the printer its broken again"
Professional Email:
Subject: Printer Maintenance Request
Dear IT Support,
I am writing to report that the printer in [location]
is not functioning properly. Could someone please
look into this issue? Thank you for your help.
Best regards,
[Your name]

---

Message: "running late to the client call sry"
Professional Email:

Puntos Clave​

Summary
  1. El zero-shot prompting funciona sin ejemplos; es ideal para tareas estándar
  2. El few-shot prompting utiliza ejemplos para demostrar patrones; es ideal para formatos personalizados
  3. 2-3 ejemplos suelen ser suficientes para la mayoría de las tareas
  4. Los ejemplos deben ser diversos, consistentes y representativos
  5. Más ejemplos = mayor costo; encuentre el número mínimo efectivo
  6. Few-shot destaca en formatos personalizados, casos límite y asegurar consistencia

¿Qué Sigue?​

En el próximo capítulo, exploraremos las estructuras básicas de prompts que proporcionan marcos para diferentes tipos de tareas.


← Anterior: Anatomía de un Prompt | Siguiente: Estructuras Básicas de Prompts →