How to Append Few-Shot Examples to a Prompt in Python
This code builds a complete LLM prompt by appending few-shot examples in alternating user/assistant format using a simple loop.
Python code
17 linesdef append_few_shot_examples(prompt: str, examples: list[tuple[str, str]], separator: str = "\n\n") -> str:
"""Append few-shot examples to a prompt in alternating user/assistant format."""
full_prompt = prompt
for user_input, assistant_output in examples:
full_prompt = f"{full_prompt}{separator}User: {user_input}{separator}Assistant: {assistant_output}"
return full_prompt
if __name__ == "__main__":
base_prompt = "Translate English to French:"
examples = [
("hello", "bonjour"),
("goodbye", "au revoir"),
("thank you", "merci"),
]
result = append_few_shot_examples(base_prompt, examples)
print(result)
Output
Translate English to French:
User: hello
Assistant: bonjour
User: goodbye
Assistant: au revoir
User: thank you
Assistant: merci
How it works
The function takes a base prompt string and a list of (user, assistant) tuples, then iterates through each tuple to build the prompt. It uses the separator parameter to add consistent spacing between the base prompt, examples, and the user/assistant labels. The f-string concatenation ensures each example is formatted identically and appended in order. Using a separator gives flexibility to customize prompt formatting based on the model or API requirements.
Common mistakes
- Forgetting to include the separator between the base prompt and the first example
- Passing examples as strings instead of tuples, causing unpacking errors
- Modifying the original prompt variable unexpectedly without reassignment
- Adding newlines inconsistently, which can alter model behavior
Variations
- Use a list comprehension with `join()` to build the entire prompt in one expression
- Add a system message prefix for chat-based APIs that require role separation
Real-world use cases
- Preparing few-shot samples for OpenAI or Anthropic API calls in production LLM applications.
- Building repeatable, testable prompts for batch inference pipelines where formatting consistency matters.
- Creating dynamic prompt templates that add context examples based on user or tenant settings.
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.