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.
Python code
21 linesfrom 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
{'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
- Use a dataclass to represent the prompt instead of a plain dictionary
- 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
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.