提示词模板
FewShotPromptTemplate/PromptTemplate
FewShotPromptTemplate(
examples=None,example_prompt=None,
prefix=None,
suffix=None,
input_variables=None
)
参数:
- examples:示例数据,list,内套字典
- example_prompt:示例数据的提示词模板
- prefix:组装提示词,示例数据前内容
- suffix:组装提示词,示例数据后内容
- input_variables:列表,注入的变量列表
实例
from langchain_core.prompts import PromptTemplate,FewShotPromptTemplate
from langchain_community.llms.tongyi import Tongyi
# 示例的模板
example_template = PromptTemplate.from_template("单词:{word}, 反义词: {antonym}")
# 示例的动态数据注入 要求是list内部套字典
examples_data = [
{"word": "大", "antonym": "小"},
{"word": "高", "antonym": "低"},
]
FewShot_Prompt = FewShotPromptTemplate(
example_prompt = example_template, #示例数据模板
examples = examples_data, #示例数据(用于动态注入)
prefix = "告诉我单词的反义词,我提供如下示例", #示例前缀
suffix = "基于前面的内容回答我,{input}的反义词", #示例后缀
input_variables=['input']
)
prompt_value = FewShot_Prompt.invoke(input={"input": "左"}).to_string()
print(prompt_value)
model = Tongyi(model="qwen-max")
print(model.invoke(input=prompt_value))
程序运行结果
D:\Programs\Python\Python314\python.exe E:\Python\LLM实例\LangChain简单使用\FewShot提示词模板.py
D:\Programs\Python\Python314\Lib\site-packages\langchain_core\_api\deprecation.py:25: UserWarning: Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.
from pydantic.v1.fields import FieldInfo as FieldInfoV1
告诉我单词的反义词,我提供如下示例
单词:大, 反义词: 小
单词:高, 反义词: 低
基于前面的内容回答我,左的反义词
左的反义词是右。
进程已结束,退出代码为 0
ChatPromptTemplate
支持注入任意数量的历史会话信息
历史会话信息并非静态的,而是随着对话的进行不断的积攒的,动态的
实例如下
from langchain_core.prompts import ChatPromptTemplate,MessagesPlaceholder
from langchain_community.chat_models.tongyi import ChatTongyi
chat_prompt_template = ChatPromptTemplate.from_messages(
[
("system","你是一个诗人,你可以作诗"),
MessagesPlaceholder("history_message"),
("human","很好,再来一首吧"),
]
)
history_date = [
("human", "你来写一个唐诗"),
("ai", "白日依山尽,黄河入海流。欲穷千里目,更上一层楼"),
("human" , "做的不错,再来一首吧"),
("ai", "千山鸟飞绝,万径人踪灭。孤舟蓑笠翁,独钓寒江雪")
]
# StringPromptValue 类对象
prompt_text_value = chat_prompt_template.invoke({"history_message": history_date}).to_string()
print(prompt_text_value)
model = ChatTongyi(model="qwen2.5-vl-3b-instruct")
res = model.invoke(prompt_text_value)
print(res.content)
实例运行效果