0Pricing
AI Engineering Academy · Leçon

Prompts zero-shot et few-shot

Comprenez la différence entre interroger directement le modèle et lui fournir des exemples, puis apprenez quand chaque approche produit de meilleurs résultats pour les tâches de classification, d’extraction et de génération.

Prompts zero-shot et few-shot est une leçon AI Engineering Academy gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage AI Engineering Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours AI Engineering Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

What Is Zero-Shot Prompting?

Zero-shot prompting means asking the model to perform a task without giving it any examples of how to do it. You simply describe the task and let the model apply its pre-trained knowledge. This works well for tasks the model has seen many times during training, such as translation, summarization, or simple classification.

For example, asking the model to Classify this review as Positive or Negative is a zero-shot prompt. The model has absorbed thousands of sentiment classification examples during pre-training, so it can perform the task without being shown examples in the prompt itself.

A Simple Zero-Shot Example

Zero-shot prompts are concise and rely on the model built-in knowledge. They work best when the task is common and unambiguous. Notice that the prompt below defines the task clearly without showing any examples of correct outputs.

import openai

client = openai.OpenAI()

prompt = 'Classify the sentiment of the following customer review.\nRespond with only one word: Positive, Negative, or Neutral.\n\nReview: The delivery was fast but the packaging was damaged.\n\nSentiment:'

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': prompt}],
    max_tokens=5
)
print(response.choices[0].message.content)  # Expected: Negative

When Zero-Shot Falls Short

Zero-shot prompting can fail when the task format is unusual, when the model must follow an uncommon output schema, or when you need consistent formatting that the model might interpret differently each run. Asking the model to extract data in a very specific JSON structure with custom field names is risky as a zero-shot prompt because the model must guess your exact intent.

Zero-shot also struggles with domain-specific jargon or niche classification categories the model may not have encountered frequently during pre-training. In these cases, providing examples dramatically improves accuracy.

What Is Few-Shot Prompting?

Few-shot prompting means providing the model with 2-8 examples of the task (input and desired output) before presenting your actual query. The examples teach the model the exact format and classification scheme you want without any fine-tuning or training required.

This is one of the most powerful and underused techniques in prompt engineering. The model uses the examples to infer the pattern and applies it to the new input. Research from the GPT-3 paper showed that performance on many tasks scaled significantly with the number of examples, up to about 8, after which gains plateau and you just waste tokens.

Few-Shot Prompt Structure

A few-shot prompt follows a consistent pattern: show N examples as input-output pairs, then present the new input and let the model complete the output. The formatting of the examples teaches the model the exact output format you expect.

import openai

client = openai.OpenAI()

prompt = ('Extract the product name and price from each sentence.\n'
          'Respond in the format: Product: <name> | Price: <price>\n\n'
          'Sentence: The blue headphones cost $79.99.\n'
          'Product: Blue Headphones | Price: $79.99\n\n'
          'Sentence: You can get the leather wallet for just $34.\n'
          'Product: Leather Wallet | Price: $34\n\n'
          'Sentence: Order the ergonomic keyboard for $129.99 today.\n')

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': prompt}],
    max_tokens=30
)
print(response.choices[0].message.content)

Choosing Good Few-Shot Examples

The quality of your examples matters as much as their quantity. Choose examples that:

  • Cover edge cases — include an example with ambiguous input so the model sees how you want it handled
  • Span the output space — if you have three classes, include at least one example of each
  • Are representative — use examples similar in style and complexity to real production inputs
  • Are consistent in format — any format inconsistency in your examples will propagate into the model output

Poorly chosen examples can actually hurt performance by misleading the model about the task distribution.

Zero-Shot vs Few-Shot: When to Use Each

Use zero-shot when: the task is common and well-defined, you want minimal token cost, or you are iterating quickly and examples are hard to collect yet. Zero-shot is also preferable when the model general knowledge should not be constrained by examples.

Use few-shot when: the output format is unusual or strict, you have domain-specific categories, zero-shot produces inconsistent formatting, or you need the model to follow a particular style or tone consistently. Few-shot is especially effective for extraction, classification, and generation with format constraints.

Few-Shot for Classification Tasks

Classification is one of the highest-value use cases for few-shot prompting. When you have custom labels that do not map to common categories, providing examples trains the model on your taxonomy. The examples below define exactly what Bug, Feature Request, and Question mean in the context of support tickets.

import openai

client = openai.OpenAI()

prompt = ('Classify the support ticket into: Bug, Feature Request, or Question.\n\n'
          'Ticket: The login button does nothing when I click it.\n'
          'Category: Bug\n\n'
          'Ticket: Can you add dark mode to the dashboard?\n'
          'Category: Feature Request\n\n'
          'Ticket: How do I export my data to CSV?\n'
          'Category: Question\n\n'
          'Ticket: The export button crashes the app every time.\n'
          'Category:')

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': prompt}],
    max_tokens=10
)
print(response.choices[0].message.content)  # Bug

One-Shot Prompting

Between zero-shot and few-shot sits one-shot prompting: providing exactly one example. This is often enough to fix formatting issues or clarify ambiguous tasks, and it costs far fewer tokens than a full few-shot prompt. One-shot is a good first escalation step when zero-shot produces unreliable results.

In practice, start with zero-shot, evaluate on a sample of real inputs, and add examples only where the model is failing. This keeps your prompts lean and token-efficient while targeting improvements where they matter most.

Dynamic Few-Shot Selection

In production systems, hardcoding the same few examples for every query is suboptimal. Dynamic few-shot selection retrieves the most similar examples to the current input from a labeled example bank using embedding similarity, then injects only those examples into the prompt.

This way, the model always sees the most relevant demonstrations for the specific input, rather than generic examples that may not match the input style or domain. This technique combines the benefits of few-shot prompting with the scalability of a retrieval system, and is sometimes called example-based retrieval-augmented prompting.

Format Constraints in Few-Shot Prompts

Few-shot prompting is the most reliable way to enforce strict output formats before you have access to structured outputs or JSON mode. By showing the model the exact format you expect — including field names, delimiters, and ordering — you dramatically increase the chance of getting parseable output.

Always end your few-shot prompt with the beginning of the expected output pattern (e.g., the opening brace of a JSON object or the first field name). This primes the model to continue the pattern rather than potentially summarizing or commenting on the task first.

Quick Check

Test your understanding of AI Engineering concepts from this lesson.

Lesson Recap

In this lesson you learned: zero-shot prompting asks the model to perform tasks from description alone, few-shot prompting provides 2-8 input-output examples to teach format and taxonomy, and dynamic few-shot selection retrieves the most relevant examples per query using embedding similarity. Next up we explore chain-of-thought prompting for complex reasoning tasks.

Questions Fréquemment Posées

La leçon « Prompts zero-shot et few-shot » est-elle gratuite ?

Oui — le texte complet de « Prompts zero-shot et few-shot » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours AI Engineering Academy, passe à CoddyKit PRO. Le cours AI Engineering Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Prompts zero-shot et few-shot » ?

Comprenez la différence entre interroger directement le modèle et lui fournir des exemples, puis apprenez quand chaque approche produit de meilleurs résultats pour les tâches de classification, d’ext… Tu pratiques AI Engineering Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer AI Engineering Academy ?

Aucune expérience préalable n'est requise. AI Engineering Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.

Combien de temps prend la leçon « Prompts zero-shot et few-shot » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon AI Engineering Academy ?

Oui. Chaque leçon AI Engineering Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Prompts zero-shot et few-shot
  2. Chaîne de pensée et raisonnement étape par étape
  3. Prompts système et définition d’une persona
  4. Itération et débogage des prompts
← Retour à AI Engineering Academy