LangChain 老喻干货店提示词工程

AutoGen、LangChain、LlamaIndex玩了一圈,越来越感觉Prompt Engineering 才是核心。欢迎大家一起学习AIGC、AGI,欢迎点赞,评论区讨论。

前言

上篇文章我们以I/O的视角来看待大模型。本文我们将继续深入LangChain在I/O的三个阶段的给力组件,让我们更好的开发AI应用。

提示词模板类型

提示词模板方便复用、接收参数、可以定制。根据用途(String 和 Chat )可以分为两类:StringPromptTemplate和BaseChatpromptTemplate(chat 有特定的结构)。再根据具体场景,我们来学习下LangChain的PromptTemplate:

  • PromptTemplate

最常用的String 提示词模板,可以接受input_variables、partial_variables。

  • ChatPromptTemplate

根据角色不同,分为ChatMessagePromptTemplate、HumanMessagePromptTemplate、AIMessagePromptTemplate和SystemMessagePrompt。

  • FewShotPromptTemplate

在prompt中加入一些"教学",教模型如何回答。fewshot 是少量样本的意思

  • PipelinePrompt

可以将几个提示组合在一起

  • 自定义模板

可以继承模板类, 开发自己的模板类

如上图,Prompts是LangChain的核心模块,我们可以从Prompts模块导入以上各种类型的模块。

python 复制代码
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,
)

# 当然直接从langchain引入也可以
from langchain import PromptTemplate

PromptTemplate

ini 复制代码
from langchain import PromptTemplate

template = """\
你是一位资深咨询顾问。
你给一个在线销售{product}的电商公司,取个好的名字?
"""
prompt = PromptTemplate.from_template(template)

print(prompt.format(product="干货"))

输出结果:

复制代码
你是一位资深咨询顾问。
你给一个在线销售干货的电商公司,取个好的名字?

这就是最简单的PromptTemplate input_variables的例子,{product}是占位符,通过from_template方法创建了一个提示词模板对象,调用对象的format方法,将传入的variable替换占位符生成最后的prompt。在产品层面,PromptTemplate 让AI程序因为提示词模板可以适用更多的应用场景。真的可以用它干点活。

我们也可以直接调用PromptTemplate构造函数直接完成prompt对象的创建,而不是调用from_template方法。

ini 复制代码
prompt = PromptTemplate(
    input_variables=["product", "age"], 
    template="你是一位资深咨询顾问。对于一个面向{age}市场的,专注于销售{product}的公司,你会推荐哪个名字?"
)
print(prompt.format(product="干货", market="老年"))

ChatPromptTemplate

各种聊天模板不同的地方主要在于它们有不同的角色(系统、用户和助理)。首条信息是系统信息,用于设置助理的身份或行为,接下来提出问题的是用户,回答问题的是大模型的助手。传给大模型的是消息对象的数组。

ini 复制代码
import openai
openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "你是一位专业食疗医生"},
        {"role": "user", "content": "请问血糖比较高午餐应该怎么吃?"},
        {"role": "assistant", "content": "一般情况下,血糖高的人午餐吃粗粮、高纤维的食物"},
        {"role": "user", "content": "高纤维的食物有哪些?"}
    ]
)

FewShot

机器学习中有Few-Shot(少量样本)、One-Shot(单样本)和Zero-Shot(零样本)的概念,用于教大模型怎么做。Zero-Shot,你希望大模型自己去悟,这便是禅宗。怪不得Facebook要请少林寺大和尚去讲AI与禅。其它就是给单个例子还是一些例子。

FewShotPromptTemplate,说白了就是方便我们将examples和template区别开来,它来组装。

ini 复制代码
# 创建FewShotPromptTemplate对象

examples = [
    {
        "food_type":"黑木耳",
        "season": "夏季",
        "benefit": "木耳生长在潮湿阴凉的环境中,可以消除血液中的热毒,起到清热解毒的功效。"
    },
    {
        "food_type": "海带",
        "season": "春季",
        "benefit":"海带有丰富的膳食纤维,有助于促进肠胃"
    }
]

# 2. 创建一个提示模板
from langchain.prompts.prompt import PromptTemplate

template="干货类型: {food_type}\n季节: {season}\n文案: {benefit}"
prompt_example = PromptTemplate(input_variables=["food_type", "season", "benefit"], 
                               template=template)
print(prompt_example.format(**example[0]))

from langchain.prompts.few_shot import FewShotPromptTemplate
prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=prompt_example,
    suffix="干货类型: {food_type}\n季节: {season}",
    input_variables=["food_type", "season"]
)
print(prompt.format(flower_type="白木耳", occasion="夏季"))

如果示例比较多, 我们可以使用示例选择器example_selector,这样可以减少token的开销,也可以增加业务的匹配性。

ini 复制代码
# 示例选择器
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
# 向量数据库 chromadb
from langchain.vectorstores import Chroma
# 嵌入
from langchain.embeddings import OpenAIEmbeddings

# 初始化示例选择器
example_selector = SemanticSimilarityExampleSelector.from_examples(
    exmples,
    OpenAIEmbeddings(),
    Chroma,
    k=1
)

# 创建一个使用示例选择器的FewShotPromptTemplate对象
prompt = FewShotPromptTemplate(
    example_selector=example_selector, 
    example_prompt=prompt_example, 
    suffix="干货类型: {food_type}\n季节: {season}", 
    input_variables=["food_type", "season"]
)
print(prompt.format(food_type="墨鱼", occasion="秋季"))

总结

  • 深入理解了提示词模板
  • 各种模板的用法
  • FewShot 可以提高回答问题的质量

参考资料

  • 黄佳老师的LangChain课
相关推荐
balmtv9 分钟前
ChatGPT与Gemini官网联网搜索技术拆解:实时信息如何被准确获取?
人工智能·chatgpt
Σίσυφος190017 分钟前
格雷码详解
人工智能
可观测性用观测云22 分钟前
观测云推出 OpenClaw 可观测插件:从黑盒到白盒,让每次 AI 执行皆有迹可循
人工智能
阿里云大数据AI技术22 分钟前
告别“金鱼记忆”:Hologres + Mem0,为大模型打造企业级长记忆引擎
人工智能·llm
周末程序猿24 分钟前
技术总结|十分钟抓包逆向分析 `Claude-Code`
人工智能
Theodore_102228 分钟前
深度学习(11):偏差与方差诊断、学习曲线
人工智能·笔记·深度学习·神经网络·机器学习·计算机视觉
weixin_4361824233 分钟前
PLC 与 DCS 国产化报告获取:工控产业情报查找指南
大数据·人工智能·国产plc
金智维科技官方1 小时前
制造业如何用Ki-AgentS智能体平台实现设备巡检自动化?
大数据·运维·人工智能
stereohomology1 小时前
大模型看大模型:推理Token的能耗用电量比对
人工智能
Hello world.Joey1 小时前
Transformer解读
人工智能·深度学习·神经网络·自然语言处理·nlp·aigc·transformer