Bootstrap

2.langchain中的prompt模板 (FewShotPromptTemplate)

本教程将介绍如何使用 LangChain 库中的 PromptTemplateFewShotPromptTemplate 来构建和运行提示(prompt),并通过示例数据展示其应用。

安装依赖

首先,确保你已经安装了 langchain 和相关依赖:

pip install langchain langchain_core langchain_chroma langchain_community

1. 创建 PromptTemplate

PromptTemplate 用于定义一个模板,该模板可以动态地插入变量。

代码示例

from langchain_core.prompts import PromptTemplate

example_prompt = PromptTemplate.from_template("Question: {question}\n{answer}")

解释

  • PromptTemplate.from_template 方法用于从给定的模板字符串创建一个 PromptTemplate 对象。
  • 模板字符串中的 {question}{answer} 是占位符,将在后续被实际数据替换。

2. 定义示例数据

示例数据是一个列表,每个元素是一个包含 questionanswer 的字典。

代码示例

examples = [
    {
        "question": "Who lived longer, Muhammad Ali or Alan Turing?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
""",
    },
    {
        "question": "When was the founder of craigslist born?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952
""",
    },
    {
        "question": "Who was the maternal grandfather of George Washington?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
""",
    },
    {
        "question": "Are both the directors of Jaws and Casino Royale from the same country?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate Answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate Answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate Answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate Answer: New Zealand.
So the final answer is: No
""",
    },
]

解释

  • 每个字典包含一个问题和对应的答案。
  • 答案部分详细描述了求解问题的中间步骤和最终答案。

3. 使用 PromptTemplate 调用示例

代码示例

print(example_prompt.invoke(examples[0]).to_string())

输出

Question: Who lived longer, Muhammad Ali or Alan Turing?

Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali

解释

  • example_prompt.invoke(examples[0]) 方法将示例数据中的第一个元素插入到模板中。
  • to_string() 方法将结果转换为字符串形式。

4. 创建 FewShotPromptTemplate

FewShotPromptTemplate 用于结合多个示例和一个后缀模板来生成最终的提示。

代码示例

from langchain_core.prompts import FewShotPromptTemplate

prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Question: {input}",
    input_variables=["input"],
)

print(
    prompt.invoke({"input": "Who was the father of Mary Ball Washington?"}).to_string()
)

输出

Question: Who lived longer, Muhammad Ali or Alan Turing?

Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali


Question: When was the founder of craigslist born?

Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952


Question: Who was the maternal grandfather of George Washington?

Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball


Question: Are both the directors of Jaws and Casino Royale from the same country?

Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate Answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate Answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate Answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate Answer: New Zealand.
So the final answer is: No


Question: Who was the father of Mary Ball Washington?

解释

  • FewShotPromptTemplate 结合了多个示例和一个后缀模板。
  • examples 参数是之前定义的示例数据。
  • example_prompt 是之前创建的 PromptTemplate
  • suffix 是一个后缀模板,用于添加到所有示例之后。
  • input_variables 定义了后缀模板中使用的变量。

5. 使用语义相似度选择示例

SemanticSimilarityExampleSelector 用于根据输入问题的语义相似度选择最相关的示例。

代码示例

from langchain_chroma import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_community.embeddings import ZhipuAIEmbeddings

embed = ZhipuAIEmbeddings(
    model="embedding-3",
    api_key="your api key",
)

example_selector = SemanticSimilarityExampleSelector.from_examples(
    examples,
    embed,
    Chroma,
    k=1,
)

question = "Who was the father of Mary Ball Washington?"
selected_examples = example_selector.select_examples({"question": question})
print(f"Examples most similar to the input: {question}")
for example in selected_examples:
    print("\n")
    for k, v in example.items():
        print(f"{k}: {v}")

输出

Examples most similar to the input: Who was the father of Mary Ball Washington?

answer: 
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball

question: Who was the maternal grandfather of George Washington?

解释

  • ZhipuAIEmbeddings 用于生成问题的嵌入向量。
  • SemanticSimilarityExampleSelector.from_examples 创建一个示例选择器,用于根据语义相似度选择示例。
  • k=1 表示选择最相似的一个示例。
  • select_examples 方法根据输入问题选择最相似的示例。

总结

本教程展示了如何使用 LangChain 中的 PromptTemplateFewShotPromptTemplate 来构建和运行提示,并通过语义相似度选择最相关的示例。这些工具在构建复杂的提示和生成高质量回答方面非常有用。希望这个教程对你有所帮助!

参考链接:https://python.langchain.com/v0.2/docs/how_to/few_shot_examples/

希望这个教程对你有所帮助!如果有任何问题,欢迎随时提问。

;