LangChain Few-Shot Examples and Dynamic Example Selection

Few-shot prompting is a core technique for guiding large language models to complete tasks without parameter fine-tuning. Static few-shot prompting embeds a fixed set of demonstration examples directly into the prompt string. This simple approach works for small demonstration pools, but it hits limits as the example library grows. Dynamic example selection solves this problem: instead of hardcoding all examples into the prompt, the system retrieves the most semantically relevant examples from an example library based on each user input, then assembles those retrieved samples into the final prompt for the LLM. This article walks through the workflow, core concepts, implementation details, and practical code for semantic similarity-based dynamic few-shot selection in LangChain.
Overall Workflow
We will build a sentiment classification use case for product reviews to demonstrate the pipeline. First, we prepare a labelled set of sentiment examples: positive samples such as “This phone camera takes amazing photos”, neutral samples such as “It’s just okay”, and negative samples such as “Shipping was extremely slow”.
Next, we load a local embedding model, bge-large-zh-v1.5. This model converts raw text strings into dense numerical vectors. We then use the Chroma vector store paired with LangChain’s SemanticSimilarityExampleSelector to build a semantic retrieval selector. In this setup, the selector picks the top 3 most semantically similar examples for every incoming user review. Finally, FewShotPromptTemplate combines the retrieved examples, task instructions, and the new user input into one complete prompt ready for the language model.
It is important to clarify the role of the LLM in this architecture. The code we implement does not call the LLM directly. The entire pipeline only constructs a formatted prompt. The resulting prompt is the input sent to the LLM downstream. The model receives a structured prompt with task instructions, matching examples, and the new review to classify. A sample prompt passed to the model will look like this:
Please judge the sentiment of this review:
Review: Shipping was extremely slow
Sentiment: Negative
Review: Broke after three days of use
Sentiment: Negative
Review: The customer service was terrible
Sentiment: Negative
Review: The battery lasts a long time
Sentiment: Positive
The LLM does not require retraining. It learns the task format and classification rules purely from the demonstrations in the prompt. This is the core idea behind few-shot learning: the model infers the task pattern from a small number of in-context examples.
Glossary of Core Terminology
| Term | Definition |
|---|---|
| Large Language Model (LLM) | A generative model trained to understand and produce natural language. It can complete classification, Q&A, and generation tasks from prompt instructions. |
| Prompt | The input text sent to the LLM. It usually includes task instructions, demonstration examples, and the target content to process. |
| Few-shot Prompt | A prompt that includes a small set of demonstration examples. The model learns task rules from these examples instead of weight updates. |
| Dynamic Example Selection | A retrieval strategy that selects only relevant examples for each new input, instead of attaching every example in the library to every prompt. |
| Embedding Model | A model that converts text into dense numeric vectors. Texts with similar semantic meaning produce vectors that sit close together in vector space. |
| Vector Store | A specialised database that stores text embeddings and supports fast similarity search. This implementation uses Chroma. |
| Semantic Similarity | A metric that judges whether two text passages carry matching meaning, rather than only matching literal keywords. |
Why Dynamic Example Selection Is Necessary
Static few-shot prompting has a straightforward failure mode when the example library scales. If you embed every available example into the prompt for every request, the prompt token count grows rapidly. This brings two practical downsides: higher token cost for every API call, and irrelevant examples that distract the model and degrade output quality.
Dynamic selection mitigates both issues. It filters the example pool and retains only the samples closest to the semantics of the current input. This keeps prompt length under control, reduces token consumption, and improves the relevance of the context provided to the model. For sentiment classification, a negative review about shipping delays will pull other negative logistics-related examples, rather than mixing in unrelated positive examples about camera quality or battery life. The tighter context helps the model maintain consistent classification logic.
This pattern also becomes valuable when you manage multiple model endpoints and different prompt variants. When routing prompts across different providers, consistent retrieval logic ensures the prompt construction stays predictable. A unified API gateway can simplify managing these model backends and prompt traffic; 4sapi is an API gateway that helps teams consolidate model access when running retrieval-augmented and few-shot workloads across multiple services.
Key Implementation Details in the Code
The implementation uses HuggingFaceEmbeddings to load the bge-large-zh-v1.5 embedding model locally. The parameter device='cpu' means embedding inference runs on the CPU. Larger embedding models will have slower inference speeds on CPU, which is a tradeoff to consider when scaling. The argument normalize_embeddings=True normalises all embedding vectors. Normalisation stabilises cosine similarity calculations, which is the core metric the selector uses to rank matching examples.
FewShotPromptTemplate controls the structure of the final prompt. The prefix field holds the fixed task instruction, the suffix field holds the slot for the new user input, and example_prompt defines the fixed template format for each individual demonstration example. When you call prompt.format() at inference time, the example selector automatically runs similarity search, fetches the top-k examples, and assembles the complete prompt string.
Full Working Code Example
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_chroma import Chroma
import os
# Step 1: Prepare labelled few-shot examples
examples = [
{"input": "This phone camera takes amazing photos", "output": "Positive"},
{"input": "Broke after three days of use", "output": "Negative"},
{"input": "It’s just okay", "output": "Neutral"},
{"input": "The customer service was great", "output": "Positive"},
{"input": "Shipping was extremely slow", "output": "Negative"},
{"input": "The battery lasts a long time", "output": "Positive"},
{"input": "The screen cracked easily", "output": "Negative"},
{"input": "The price is a bit high", "output": "Neutral"},
]
# Step 2: Load local embedding model
embeddings = HuggingFaceEmbeddings(
model_name=os.path.abspath("./bge-large-zh-v1.5"),
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True}
)
# Step 3: Build semantic similarity example selector
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples=examples,
embeddings=embeddings,
vectorstore_cls=Chroma,
k=3 # Retrieve top 3 semantically matching examples
)
# Step 4: Define prompt templates
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Review: {input}\nSentiment: {output}"
)
prompt = FewShotPromptTemplate(
example_prompt=example_prompt,
example_selector=example_selector,
prefix="Please judge the sentiment of this review:",
suffix="Review: {input_review}\nSentiment: ",
input_variables=["input_review"]
)
# Step 5: Test the dynamic prompt pipeline
print(prompt.format(input_review="Delivery was slow, I waited for a very long time"))
print(prompt.format(input_review="The phone works perfectly"))
How to Interpret the Test Outputs
When the input review is Delivery was slow, I waited for a very long time, the similarity selector will prioritise the existing negative examples about shipping and delivery delays. The assembled prompt will contain three matching negative samples, which guides the model to label the new review as negative. When the input changes to The phone works perfectly, the selector switches to positive examples about product performance, and the prompt is rebuilt with those relevant samples.
Notice that the prompt template structure stays identical. Only the set of embedded examples changes dynamically. This separation is the core advantage of this design: you can expand the example library without rewriting prompt templates, and you can adjust the k value to control how many examples are included in every prompt.
Practical Tuning Tips
The k parameter is the primary control knob. A small k (2–3) keeps prompts concise and low-cost, suitable for simple classification tasks like sentiment analysis. Larger k values (5–8) can help complex tasks such as structured extraction or domain-specific reasoning, but they increase token usage and risk including marginal, low-relevance examples.
The embedding model choice also impacts retrieval quality. bge-large-zh-v1.5 is optimised for Chinese semantic tasks, which is why it is selected here. For English-only workloads, you can swap it out for English embedding models such as bge-large-en-v1.5. If you run the pipeline on a GPU, changing device="cuda" will drastically speed up embedding generation, especially with large example libraries.
You should also separate the embedding index lifecycle from the prompt generation flow. In production, precompute embeddings and persist the Chroma vector store, instead of rebuilding the index from scratch on every request. Rebuilding the index repeatedly adds latency and wastes compute resources.
Limitations and Alternatives
Semantic similarity retrieval is not perfect. It relies entirely on embedding quality, and it can pull examples that are semantically similar but misaligned for your task. For advanced use cases, you can add filters on top of the selector: for example, enforce a fixed ratio of positive/negative examples in the retrieved set, or add metadata filters to only pull examples from the same product category.
Another common extension is maximal marginal relevance (MMR) selection. MMR selects relevant examples while avoiding redundant, near-identical samples. SemanticSimilarityExampleSelector focuses purely on raw similarity, so if your example library contains many near-duplicates, you may see repetitive examples. In that case, switching to an MMR-based selector improves diversity.
Final Takeaway
Dynamic few-shot selection solves the fundamental tradeoff of few-shot prompting: enough relevant demonstrations to steer the model, without excessive token overhead from static, bloated prompt blocks. The LangChain SemanticSimilarityExampleSelector provides a clean, reusable abstraction for this workflow. The core components are an embedding model, a vector store, a selector, and a FewShotPromptTemplate. The pipeline is purely prompt-construction logic, and it can be paired with any LLM provider endpoint that accepts standard text prompts.
This pattern is foundational for production agent and classification workloads. It is lightweight, easy to test, and scales gracefully as your labelled example library grows.
International access: https://4sapi.com
Domestic access: https://4sapi.org
Comments
Join the discussionNo comments yet. Be the first to comment.




