青训营X豆包MarsCode 技术训练营笔记(2) | 豆包MarsCode AI刷题

77 阅读3分钟

今天,总结LangChain实战课第5-6节学习心得。第五-六章的主要内容是提示工程。

总结一:如何让模型生成结构化的输出。 提示词遵从的原则如下:

  1. 指示表达清晰
  2. 给模型提供参考示例
  3. 将复杂任务细化成子任务
  4. 给大模型思考的时间
  5. 使用外部工具辅助模型
  6. 反复迭代问题

一个良好的提示框架包含:

  1. 指令:告诉模型做什么任务,该任务怎么做,比如“你是一个学术专家,你需要。。。”
  2. 上下文:模型的外部知识来源,
  3. 提示输入:把指令转换成具体问题,便于复用模板,作为变量传给模板,形成具体的提示。
  4. 输出指示器:表示要生成的文本开始,指示模型从这里开始生成你的答案。

langchain提供了四个提示模板:

image.png

from langchain.prompts.prompt import PromptTemplate
from langchain.prompts import FewShotPromptTemplate
from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts import ChatPromptTemplate
from langchain.prompts import (
    ChatMessagePromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
 

总结2:模板使用心得

  1. 使用 PromptTemplate
template = """\ 你是业务咨询顾问。 你给一个销售{product}的电商公司,起一个好的名字? """ 
prompt = PromptTemplate.from_template(template)
print(prompt.format(product="鲜花"))

这里面{product}是占位符,通过from_template方法,我们创建了模板提示的一个对象,通过prompt.format方法将填入占位符中的文字。

  1. 使用 ChatPromptTemplate
template="你是一位专业顾问,负责为专注于{product}的公司起名。" 
system_message_prompt = SystemMessagePromptTemplate.from_template(template) 
human_template="公司主打产品是{product_detail}。" 
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) 
prompt_template = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) 
# 格式化提示消息生成提示 prompt = prompt_template.format_prompt(product="鲜花装饰", product_detail="创新的鲜花设计。").to_messages()

这个模板的特色在于可以选择不同的角色,比如代码里的系统角色和人类角色。

  1. FewShot少样本模板与使用FewShotPromptTemplate
  • 在Few-Shot学习设置中,模型会被给予几个示例,以帮助模型理解任务,并生成正确的响应。
  • 在Zero-Shot学习设置中,模型只根据任务的描述生成响应,不需要任何示例。

首先我们会创建几个samples作为示例,sample为列表,包含了四个字典,每一个字典代表一种花的类型、合适的场合以及对应的广告文案。

其次,我们需要把字典中的示例转化为提示模板,形成具体的Langchain提示。如下代码所示:

template="鲜花类型: {flower_type}\n场合: {occasion}\n文案: {ad_copy}" 
prompt_sample = PromptTemplate(input_variables=["flower_type", "occasion", "ad_copy"], template=template) 
print(prompt_sample.format(**samples[0]))

在这里,我们用samples[0]中的数据替换了模板中的变量,生成了一个完整的提示。

最后我们要创建FewShotPromptTemplate对象,通过使用上一步骤中创建的prompt_sample,以及samples列表中的所有示例, 创建一个FewShotPromptTemplate对象,生成更复杂的提示。

from langchain.prompts.few_shot import FewShotPromptTemplate
prompt = FewShotPromptTemplate(
    examples=samples,
    example_prompt=prompt_sample,
    suffix="鲜花类型: {flower_type}\n场合: {occasion}",
    input_variables=["flower_type", "occasion"]
)
print(prompt.format(flower_type="野玫瑰", occasion="爱情"))

总结3:使用思维链CoT

第一种是少样本思维链:给出一个模板:问题理解-》信息搜索-》决策制定-》生成销售链表,然后告诉模型要一步一步思考。 该思维链能够引导AI从理解问题,到搜索信息最后到指定决策,生成销售列表。这种方法可以使得逻辑更加清晰,细节化,符合用户的需求。

第二种是零样本思维链CoT:直接告诉模型要一步一步地思考,慢慢地推理。

第三种是思维树:ToT 框架为每个任务定义具体的思维步骤和每个步骤的候选项数量。能够对于每一个环节都提供多个候选方案,这种方式的优势在于,模型可以不仅限于输入和输出的内容,而是可以观察自己的思考过程,进行相应的评估,然后自己调整,以适应用户需求,生成更优质的答案。