Module 3 Lesson 4: Few-Shot Prompting
Leading by Example. How to provide the model with sample Q&A pairs to enforce style and accuracy.
Few-Shot Prompting: Learning in Real-Time
Sometimes, no matter how much "System Instruction" you give a model, it still fails to follow your specific style. In these cases, you use Few-Shot Prompting. You provide the model with 3 to 5 examples of "Input -> Output" pairs so it can hallucinate the pattern.
1. The Anatomy of a Few-Shot Prompt
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
# 1. Define the format for ONE example
example_prompt = PromptTemplate.from_template("Input: {input}\nOutput: {output}")
# 2. Provide the EXAMPLES
examples = [
{"input": "happy", "output": "sad"},
{"input": "tall", "output": "short"}
]
# 3. Assemble the FewShot Template
prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="Input: {word}\nOutput:",
input_variables=["word"]
)
print(prompt.format(word="hot"))
# Output: "Input: happy\nOutput: sad\nInput: tall\nOutput: short\nInput: hot\nOutput:"
2. When to use Few-Shotting
- Sentiment Analysis: "Is this comment positive? Example A: Yes..."
- Code Generation: Show the model exactly how you want your variable names formatted.
- Tone Consistency: If your agent must speak like a specific brand or character.
3. Dynamic Few-Shotting (Advanced)
What if you have 1,000 examples? You can't put all of them in the prompt; it would be too expensive and the model would get confused.
- We use an Example Selector (often powered by a Vector DB - Module 15) to find the 2-3 most "relevant" examples for the current user query.
4. Visualizing the Pattern Match
graph LR
User[Query: 'Fast'] --> Selection[Pick 2 antonym examples]
Selection --> Final[Big Prompt with examples]
Final --> LLM[Pattern Recognition]
LLM --> Result[Output: 'Slow']
5. Engineering Tip: Quality over Quantity
It is better to have 3 perfect examples than 20 mediocre examples. If your examples are sloppy, the agent's output will be sloppy.
Key Takeaways
- Few-Shotting is the most powerful way to control output format and style.
- PromptTemplate is used to define how each individual example is printed.
- The Suffix is where the actual user query is placed.
- Use Dynamic Selection if your example database is large.