iTranslated by AI
Implementing Optimal Few-Shot Prompting Automatically with LangChain
Since the emergence of ChatGPT, the term "Prompt Engineering" has been drawing a lot of attention! Prompt engineering refers to optimizing prompts (instructions) to elicit the desired answers from Large Language Models (LLMs). To obtain accurate responses, how you frame your questions or instructions is a very crucial element!
few-shot prompting
Are you familiar with a technique called "few-shot prompting" among the various prompt engineering methods?
The details are explained very clearly in the following link, so please check it out if you're interested!
By explicitly providing output formats and specific answer examples, few-shot prompting allows you to get the desired answers with higher precision.
Dynamic few-shot prompting
I recently found an interesting tool in LangChain related to few-shot prompting, so I'd like to share it! It's called "Dynamic few-shot prompting," which selects the most suitable few-shot examples from a pre-prepared set based on the input prompt.
Here is the official documentation:
What is LangChain?
LangChain is a library for efficiently extending the capabilities of language models like ChatGPT. Using this tool, challenges of language models—such as handling long inputs or complex mathematical problems—can be solved efficiently with a small amount of code.
Let's try it out!
The required libraries are listed below.
pip install langchain
pip install faiss-cpu
pip install openai
You will also need an OpenAI API key! If you're not sure how to obtain an OpenAI API key, please refer to other articles to get one.
The final code is shown below. This code is a compilation of what is described in the official documentation.
from langchain.prompts import SemanticSimilarityExampleSelector
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
FewShotChatMessagePromptTemplate,
ChatPromptTemplate,
)
import openai
openai.api_key = 'your-api-key-here'
# Define few-shot prompting examples
examples = [
{"input": "2+2", "output": "4"},
{"input": "2+3", "output": "5"},
{"input": "2+4", "output": "6"},
{"input": "What did the cow say to the moon?", "output": "nothing at all"},
{"input": "Write me a poem about the moon",
"output": "One for the moon, and one for me, who are we to talk about the moon?",},
]
# Concatenate input and output to create a list for vectorization
to_vectorize = [" ".join(example.values()) for example in examples]
# Initialize OpenAI embedding model
embeddings = OpenAIEmbeddings()
# Vectorize example data and save to Chroma vector store
vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)
# Initialize a selector based on semantic similarity. k indicates the number of top-k similar examples to select.
example_selector = SemanticSimilarityExampleSelector(
vectorstore=vectorstore,
k=2,
)
# Define message prompt template
few_shot_prompt = FewShotChatMessagePromptTemplate(
input_variables=["input"],
example_selector=example_selector,
example_prompt=ChatPromptTemplate.from_messages(
[("human", "{input}"), ("ai", "{output}")]
),
)
# Define the final chat prompt template
final_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a wondrous wizard of math."),
few_shot_prompt,
("human", "{input}"),
]
)
# Chain the chat model and the prompt template
chain = final_prompt | ChatOpenAI(temperature=0.0, model="gpt-3.5-turbo")
# Send a question using the chain and display the result
print(chain.invoke({"input": "What's 3+3?"}).content)
Let me explain the actual flow!
① Prepare multiple sets of inputs and outputs used for few-shot prompting in advance and vectorize them.
There are various models for vectorization, but we will use OpenAI's Embedding model.
examples = [
{"input": "2+2", "output": "4"},
{"input": "2+3", "output": "5"},
{"input": "2+4", "output": "6"},
{"input": "What did the cow say to the moon?", "output": "nothing at all"},
{"input": "Write me a poem about the moon",
"output": "One for the moon, and one for me, who are we to talk about the moon?",},
]
to_vectorize = [" ".join(example.values()) for example in examples]
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)
② This time, the prompt is "What's 3+3?". (We will use a LangChain tool called a chain.)
Looking at the examples, we would want it to bring in one of the first three. In that case, the answer should be "6"!
chain.invoke({"input": "What's 3+3?"}).content
③ Select the ones to use for few-shot prompting from the previously vectorized list.
The function called SemanticSimilarityExampleSelector ranks inputs by their similarity to the prompt "What's 3+3?" and extracts the specified number of input/output sets from the top. You can specify how many to select with k. In this case, we specify 2.
few_shot_prompt = FewShotChatMessagePromptTemplate(
input_variables=["input"],
example_selector= SemanticSimilarityExampleSelector(vectorstore=vectorstore,k=2),
example_prompt=ChatPromptTemplate.from_messages(
[("human", "{input}"), ("ai", "{output}")]
),)
④ Insert the selected few_shot_prompt between the system prompt and your own prompt.
final_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a wondrous wizard of math."),
few_shot_prompt,
("human", "{input}"),
]
)
⑤ Then the final prompt is created and passed to the LLM.
chain = final_prompt | ChatOpenAI(temperature=0.0, model="gpt-3.5-turbo")
The response that came out was:
3
We got the response we were hoping for!
If you're curious whether the most suitable few-shot prompting is actually being performed, you can check it as follows!
print(example_selector.select_examples({"input": "What's 3+3?"}))
# Output [{'input': '2+3', 'output': '5'}, {'input': '2+2', 'output': '4'}]
Vectorization incurs a cost every time it is performed (though it is minimal compared to the chat cost).
If the list of inputs and outputs is fixed, it is a good idea to save it locally and load it whenever the code is executed! The official documentation uses a database called Chroma, but since it doesn't seem to support saving easily in this context, we will use FAISS DB instead.
The following code saves the vector information in a folder named "examples".
from langchain.vectorstores import FAISS
vectorstore = FAISS.from_texts(to_vectorize, embeddings, metadatas=examples)
vectorstore.save_local("./examples")
After running this, you should see faiss and pickle files saved in a folder named "examples"!
To load it, use the following code:
vectorstore = FAISS.load_local("./examples", embeddings)
With this, you no longer need to vectorize the examples list every time you run the code!
(*Note: The vectorization of the prompt itself still needs to be performed with each execution.)
Based on my experience with few-shot prompting, I feel that increasing the number of examples is not always beneficial. Specifically, I believe that 1-shot or 2-shot prompting offers the best balance. Increasing the number of examples increases the token count (cost), and I also feel that the desired answer can sometimes be negatively influenced by other examples.
I decided to introduce this tool because I thought it was a great solution when I came across it!
This might be a slightly niche technique, but I think it's worth knowing. Please give it a try! Happy coding!
Discussion