How to Build a Zero-Shot Classification Prompt in Python

Creates a prompt for zero-shot text classification by pairing input text with candidate labels and a hypothesis template.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 13 views 0 copies

Python code

21 lines
Python 3.9+
from typing import Dict, List


def build_zero_shot_prompt(
    text: str,
    candidate_labels: List[str],
    hypothesis_template: str = "This is about {}.",
) -> Dict[str, List[str]]:
    """Build a prompt ready for zero-shot classification."""
    return {
        "sequences": text,
        "candidate_labels": candidate_labels,
        "hypothesis_template": hypothesis_template,
    }


if __name__ == "__main__":
    sample_text = "A young child learns how to ride a bicycle in the park."
    labels = ["sports", "education", "nature"]
    prompt = build_zero_shot_prompt(sample_text, labels)
    print(prompt)

Output

stdout
{'sequences': 'A young child learns how to ride a bicycle in the park.', 'candidate_labels': ['sports', 'education', 'nature'], 'hypothesis_template': 'This is about {}.'}

How it works

The function bundles text, candidate labels, and a hypothesis template into a dictionary that mimics Hugging Face's zero-shot pipeline input format. The hypothesis template with {} lets the model form a natural-language premise like 'This is about sports.' Keeping the template constant for all labels ensures fair comparisons. The return type hints clarify the expected shape for callers and static checkers.

Common mistakes

  • Using a hypothesis template without the `{}` placeholder
  • Passing labels as a single string instead of a list
  • Forgetting to import Dict and List when using type hints

Variations

  1. Use a dataclass to represent the prompt instead of a plain dictionary
  2. Add a `multi_class` flag to control mutually exclusive vs independent classification

Real-world use cases

  • Classifying incoming support tickets into predefined categories before routing to a team.
  • Filtering user-generated content into topics for moderation or recommendation engines.
  • Pre-labeling dataset examples before sending them to a human-in-the-loop review.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.