一、简介
提示词工程在利用 LangChain 与大型语言模型交互中起着关键作用,通过精心设计提示词,可以引导模型生成更准确、更符合预期的输出,从而提升应用的效果和用户体验。
二、基本提示词调用
可以使用 LangChain 提供的 PromptTemplate
来构建基本的提示词模板,例如:
from langchain.prompts import PromptTemplatetemplate = "请根据下面的主题写一篇小红书营销的短文:{topic}"
prompt = PromptTemplate.from_template(template)formatted_prompt = prompt.format(topic="康师傅绿茶")
print(formatted_prompt)
三、Few-Shot 提示词模板
Few-Shot 提示词模板通过提供少量示例来引导模型生成特定格式或风格的输出。以下是创建 Few-Shot 提示词模板的示例:
from langchain.prompts import FewShotPromptTemplate, PromptTemplateexamples = [{"query": "How are you?","answer": "I can't complain but sometimes I still do."},{"query": "What time is it?","answer": "It's time to get a watch."}
]example_template = """
User: {query}
AI: {answer}
"""example_prompt = PromptTemplate(input_variables=["query", "answer"],template=example_template
)prefix = "The following are excerpts from conversations with an AI assistant. The assistant is typically sarcastic and witty, producing creative and funny responses to the users questions. Here are some examples:"suffix = "User: {query}\nAI:"few_shot_prompt_template = FewShotPromptTemplate(examples=examples,example_prompt=example_prompt,prefix=prefix,suffix=suffix,input_variables=["query"],example_separator="\n\n"
)query = "What is the meaning of life?"
print(few_shot_prompt_template.format(query=query))
四、组合提示词模板
组合提示词模板可以将提示词分成不同层级,每个层级代表不同维度,以更细化地控制模型的生成。例如:
from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts.prompt import PromptTemplate# 第一层设计(特征)
character_template = "你是{persion},你有着{char}."
character_prompt = PromptTemplate.from_template(character_template)# 第二层设计(行为)
behavior_template = "你要遵循以下行为:{behavior_list}"
behavior_prompt = PromptTemplate.from_template(behavior_template)# 第三层设计(禁止)
prohibit_template = "你不许有以下行为:{prohibit_list}"
prohibit_prompt = PromptTemplate.from_template(prohibit_template)# 将三层结合起来
input_prompts = [("character", character_prompt),("behavior", behavior_prompt),("prohibit", prohibit_prompt)
]full_template = "{character}\n{behavior}\n{prohibit}"
full_prompt = PromptTemplate.from_template(full_template)pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts)
五、应用场景
- 内容创作:通过提示词工程,可以生成各种类型的内容,如营销文案、新闻报道、故事创作等。例如,为小红书生成营销短文的提示词模板,可以根据不同的主题生成相应的内容。
- 数据分析:可以利用提示词工程让模型对数据进行分析和解读,生成数据分析报告或可视化图表的描述。
- 客户服务:在客户服务领域,通过提示词工程可以生成自动回复、解答常见问题等,提高客户服务的效率和质量。
六、 优化与注意事项
- 优化提示词:不断测试和优化提示词,以获得更好的生成结果。可以尝试不同的提示词结构、语言风格等。
- 控制生成长度:通过设置模型的参数,如
max_token
等,来控制生成内容的长度。 - 处理不确定性:对于一些不确定或模糊的问题,可以在提示词中加入相应的处理机制,如让模型给出多种可能的答案或进行进一步的澄清。