Langchain实现FewShot提示词模板

Title Langchain实现FewShot提示词模板
Framework Langchain
User wy8817399@vip.qq.com
Id 53
Created 2/19/26, 6:30 AM
Modified 2/19/26, 6:42 AM
Published Yes
Content
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate
from langchain_community.llms.tongyi import Tongyi
import os
from dotenv import load_dotenv
load_dotenv()

#示例的模板
example_template = PromptTemplate.from_template(
"单词:{word},反义词:{antonym}"
)

#示例的数据动态注入
example_data = [
{"word": "", "antonym": ""},
{"word": "", "antonym": ""},
]


few_shot_template = FewShotPromptTemplate(
# 提示词数据模板
example_prompt = example_template,
# 提示词的数据
examples = example_data,
# 示例之前的提示词
prefix = "告知我单词的反义词,我提供如下的示例:",
# 示例之后的提示词
suffix = "基于前面的示例告诉我,{input_word}的反义词是?",
# 提示词的输入变量
input_variables =["input_word"]
)

prompt_text = few_shot_template.format(input_word="")
# print(prompt_text)

model = Tongyi(
model="qwen-max",
)

print(model.invoke(input = prompt_text))