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.

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

Python code

17 lines
Python 3.9+
def 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

stdout
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

  1. Use a list comprehension with `join()` to build the entire prompt in one expression
  2. 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

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.