FewShotPromptTemplate

What it is A FewShotPromptTemplate is a type of prompt template that shows the AI a few examples of question-and-answer pairs before asking a new question. It helps the model understand the pattern you want it to follow.

Why it exists LLMs sometimes give inconsistent answers if they don’t know the format or style you want. Few-shot prompting teaches the model with concrete examples, improving accuracy and consistency without needing full training.

Real-world analogy It’s like showing a student a few solved math problems before asking them a new one. The examples guide the student on how to approach similar problems.

Minimal beginner example

import os
from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate

load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")

llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", api_key=api_key)

examples = [
    {"question": "Who lived longer, Steve Jobs or Einstein?", "answer": "Einstein"},
    {"question": "When was Naver's founder born?", "answer": "June 22, 1967"},
]

example_template = "Q:{question}\nA:{answer}\n"

few_shot_prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=PromptTemplate.from_template(example_template),
    prefix="You are a helpful assistant. Answer the question using examples below:\n",
    suffix="Now answer this question: {new_question}",
    input_variables=["new_question"]
)

final_prompt = few_shot_prompt.format(new_question="Who directed Parasite?")
response = llm.invoke(final_prompt)

print(response.content)

The model sees examples first, so it can answer the new question in the same format.

Small LangChain workflow

  1. Define a PromptTemplate for one example.

  2. Provide multiple examples in FewShotPromptTemplate.

  3. Feed it to the LLM.

  4. Use the AI’s output in your chain or workflow.

Common beginner mistakes

  • Providing too few or inconsistent examples—model may misinterpret.

  • Forgetting to match input_variables in both template and few-shot wrapper.

  • Making examples too long—can overwhelm the model.

When to use this vs alternatives

  • Use FewShotPromptTemplate when you want the AI to follow a specific format or style.

  • Use PromptTemplate for single prompts without examples.

  • Use ChatPromptTemplate if you’re working with role-based chats.

Last updated