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课
相关推荐
渲吧云渲染2 小时前
SaaS模式重构工业软件竞争规则,助力中小企业快速实现数字化转型
大数据·人工智能·sass
算家云2 小时前
DeepSeek-OCR本地部署教程:DeepSeek突破性开创上下文光学压缩,10倍效率重构文本处理范式
人工智能·计算机视觉·算家云·模型部署教程·镜像社区·deepseek-ocr
AgeClub2 小时前
1.2亿老人需助听器:本土品牌如何以AI破局,重构巨头垄断市场?
人工智能
PPIO派欧云3 小时前
PPIO上线Qwen-VL-8B/30B、GLM-4.5-Air等多款中小尺寸模型
人工智能
chenchihwen4 小时前
AI代码开发宝库系列:FAISS向量数据库
数据库·人工智能·python·faiss·1024程序员节
张登杰踩5 小时前
工业产品表面缺陷检测方法综述:从传统视觉到深度学习
人工智能·深度学习
神秘的土鸡5 小时前
从数据仓库到数据中台再到数据飞轮:我的数据技术成长之路
java·服务器·aigc·数据库架构·1024程序员节
sponge'5 小时前
opencv学习笔记6:SVM分类器
人工智能·机器学习·支持向量机·1024程序员节
zandy10115 小时前
2025年AI IDE的深度评测与推荐:从单一功能效率转向生态壁垒
ide·人工智能