pythonbeginner

Prompt Template Engineering Patterns

Design reusable, parameterized prompt templates for consistent LLM outputs.

python
from string import Template
from typing import Dict, Any

# Simple template with few-shot examples
CLASSIFICATION_PROMPT = Template("""
Classify the following text into one of these categories: $categories

Examples:
$examples

Text to classify: "$text"

Respond with ONLY the category name.
""")

def build_classification_prompt(
    text: str,
    categories: list[str],
    examples: list[dict]
) -> str:
    example_str = "\n".join(
        f'  "{ex["text"]}" -> {ex["category"]}'
        for ex in examples
    )
    return CLASSIFICATION_PROMPT.substitute(
        categories=", ".join(categories),
        examples=example_str,
        text=text
    )

# Chain-of-thought template
COT_PROMPT = """Solve this step by step.

Problem: {problem}

Think through each step:
1. Identify the key information
2. Determine the approach
3. Execute the solution
4. Verify the answer

Solution:"""

prompt = build_classification_prompt(
    text="The stock market crashed today",
    categories=["finance", "sports", "tech", "politics"],
    examples=[
        {"text": "Apple released new iPhone", "category": "tech"},
        {"text": "Lakers won the championship", "category": "sports"}
    ]
)
print(prompt)

Use Cases

  • Consistent LLM outputs
  • Reusable prompts
  • Classification tasks

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.