2.langchain中的prompt模板 (FewShotPromptTemplate)

devtools/2024/11/23 8:09:38/

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

安装依赖

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

pip install langchain langchain_core langchain_chroma langchain_community

1. 创建 PromptTemplate

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

代码示例

from langchain_core.prompts import PromptTemplateexample_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 FewShotPromptTemplateprompt = 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 AliQuestion: 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, 1952Question: 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 BallQuestion: 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: NoQuestion: 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 ZhipuAIEmbeddingsembed = 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 Ballquestion: 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/

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


http://www.ppmy.cn/devtools/136243.html

相关文章

MagicDraw2022.x树节点显示中文乱码问题及解决方式

MagicDraw2022.x树节点显示中文乱码问题及解决方式 文章目录 MagicDraw2022.x树节点显示中文乱码问题及解决方式1. 乱码问题2. 原因跟MagicDraw2022.x默认主题有关3. 选择Metal主题问题解决 1. 乱码问题 2. 原因跟MagicDraw2022.x默认主题有关 MagicDraw2022.x安装完成后默认主…

Android开发教程案例源码分享-匹配动画多个头像飘动效果

Android开发教程案例源码分享-匹配动画多个头像飘动效果 匹配往往出现多个头像飘动,吸引人点击,有时出现的位置还不固定 一、思路: 用MotionLayout 二、效果图: 看视频更直观点: Android开发教程案例源码分享-匹配…

解决前后端发版本时候,手动清除浏览器缓存

在.html页面中添加标签 后端配置nginx,让index.html不缓存 location /index.html { add_header Cache-Control “no-cache, no-store”; }在vite.config.ts中添加 rollupOpyions: { output: { // 输出编译后的文件名称:【文件名称.时间戳】、【文件名称.版本号.…

【AI系统】GPU 架构回顾(从2018年-2024年)

Turing 架构 2018 年 Turing 图灵架构发布,采用 TSMC 12 nm 工艺,总共 18.6 亿个晶体管。在 PC 游戏、专业图形应用程序和深度学习推理方面,效率和性能都取得了重大进步。相比上一代 Volta 架构主要更新了 Tensor Core(专门为执行…

自动化立体仓库:详解

导语 大家好,我是社长,老K。专注分享智能制造和智能仓储物流等内容。 新书《智能物流系统构成与技术实践》人俱乐部 完整版文件和更多学习资料,请球友到知识星球【智能仓储物流技术研习社】自行下载。 自动化立体仓库(Automated S…

Kafka:分布式消息系统的核心原理与安装部署

Kafka:分布式消息系统的核心原理与安装部署-CSDN博客 自定义 Kafka 脚本 kf-use.sh 的解析与功能与应用示例-CSDN博客 Kafka 生产者全面解析:从基础原理到高级实践-CSDN博客 Kafka 生产者优化与数据处理经验-CSDN博客 Kafka 工作流程解析&#xff1a…

Rust 智能指针

Rust 智能指针 引言 Rust 是一种系统编程语言,以其内存安全性、并发性和高性能而闻名。Rust 的核心特性之一是其独特的所有权模型,它确保了内存安全,同时避免了垃圾收集。在 Rust 中,智能指针是一种特殊的数据结构,它们不仅存储数据,还负责管理数据的生命周期。智能指针…

不完全竞争市场

垄断竞争市场 垄断竞争市场的特征 在垄断竞争市场上,大量厂商通过销售有差别的产品竞争,产品之间高度替代但又不是完全替代厂商可以自由进出,会限制在位企业的市场势力和盈利能力。 垄断竞争市场的短期均衡 因为生产差异化产品&#xff0…