Skip to content

Few Shot Prompting

Few Shot Prompting is a technique used to generate answers for complex questions by providing a set of example prompts and answers. By leveraging the power of few-shot learning, models can generalize from these examples and provide accurate responses to new questions.

Code Demo

The following code demonstrates how to use Few Shot Prompting with the LangChain library:

from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate

examples = [
  {
    "question": "When was the founder of craigslist born?",
    "answer": "December 6, 1952"
  },
  {
    "question": "Who was the maternal grandfather of George Washington?",
    "answer": "Joseph Ball"
  },
  {
    "question": "Are both the directors of Jaws and Casino Royale from the same country?",
    "answer": "No"
  }
]

prompt_template = FewShotPromptTemplate(examples)
example_prompt = PromptTemplate(input_variables=["question", "answer"], template="Question: {question}\n{answer}")

question = "What is the capital of France?"
answer = prompt_template.generate_response(question)

output_prompt = example_prompt.render(question=question, answer=answer)

Here, we define a list of examples, each containing a question and its corresponding answer. We create a FewShotPromptTemplate instance and pass the examples to it. We then provide a new question to the FewShotPromptTemplate instance to generate a response. This allows the model to generate an accurate answer by leveraging the information from the provided examples.

Summary

Few Shot Prompting is a powerful technique that enables models to handle complex questions and generate accurate responses with minimal labeled data. By leveraging the capabilities of Few Shot Prompting, developers can unlock the potential of their models in a variety of domains and applications, making it easier to extract tailored insights from unstructured text data.