第二章 提示工程(1)

Langchain六大核心模块:提示、模型、存储、索引、链和代理。其实,我理解核心是提示工程。应该说其他核心模块都是基于提示工程有针对性打造的。另外一个核心就是链。

2.1、提示模板(PromptTemplate)

2.1.1 管理 LLM 的提示

调用 LLM 是很好的第一步,但这仅仅是个开始。注本文示例代码在VS Code(安装了笔记本插件,文件扩展名为.ipynb)中验证过。

from ChatGLM import ChatGLM2

llm=ChatGLM2()

llm("你好")

输出如下:'你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。'

通常在应用程序中使用 LLM 时,不会将用户输入直接发送到 LLM。相反,您可能接受用户输入并构造一个提示,然后将其发送给 LLM。

例如,有这样一个例子,询问一家生产某类产品的公司的名称。在这个虚构的服务中,我们希望只获取描述公司业务的用户输入,比如电动车,然后用这些信息格式化提示符。

使用LangChain,这个事情变得很简单!

首先让我们定义提示模板:

提示模板,template,使用{变量}来获取用户的输入

什么是提示模板?#

提示模板是生成提示的可重复方法。它包含一个文本字符串(“模板”),该字符串可以从最终用户那里接收一组参数并生成提示。

提示模板可能包含:

对语言模型的指导,

一组少量示例,以帮助语言模型生成更好的响应,

对语言模型的提问。

以下代码片段包含提示模板的示例:

from langchain import LLMChain, PromptTemplate

template="""

假设你是新公司命名咨询师,请给生产{product}的新公司取个好名字?

"""

prompt=PromptTemplate(

    input_variables=["product"],

    template=template

)

llm_chain=LLMChain(

    prompt=prompt,

    llm=llm

)

product="电动汽车"

print(llm_chain.run(product))

输出:

给生产电动汽车的新公司取一个好名字需要考虑多个方面,如公司的使命、目标、产品、市场和竞争等。以下是一些可能适合新公司的名字:1. Prodigy Electric vehicles2. Energize Networks3. AutoEon Motorworks4. MotionEon5. AutoNexus Motors6. ElectraFlow Energy Solutions7.清洁运输 Solutions8. Neural Energy9. AutoFuelEfficiency10. QuantumMotors希望这些名字可以启发您选择一个适合您公司的名字。

我么给变量product赋值电动汽车,然后填充提示模板。构造出“假设你是新公司命名咨询师,请给生产电动汽车的新公司取个好名字?”但是结果不理想,有中文,有英文,英文名字中还夹杂中文,很不专业。我们把模板template="""

假设你是新公司命名咨询师,请给生产{product}的新公司取个好名字?

""" 改成如下:

template="""

假设你是新公司命名咨询师,请给生产{product}的新公司使用中文取个好名字?

"""多了一个“使用中文”我么再看看结果:


给生产电动汽车的新公司使用中文取个好名字,可以参考下述建议:1. 瑞驰(RuiChi):瑞字代表吉祥、卓越,驰字代表奔跑、自由,寓意公司的汽车产品能够自由奔跑,追求卓越。2. 电动汽车之路(Electric Vehicles Road):简洁明了的名字,直接表达公司的主要业务。3. 电动之旅(Electric Journey):给人以愉悦、轻松的氛围,同时强调电动汽车的特点。4. 创捷(Chuangjie):创字代表创新、突破,捷字代表快速、流畅,寓意公司能够创新突破,汽车产品能够快速流畅。5. 智迈(Zhaimai):智代表智慧、聪明,迈代表步伐,寓意公司有着高超的智慧,为客户提供聪明的驾驶体验。

貌似还不错。这回是中文为主,同时提供英文名称,但是用括号括起来了,是不是好点了。

2.1.2 创建提示模板

您可以使用PromptTemplate类创建简单的硬编码提示。提示模板可以使用任意数量的输入变量,并可以进行格式化以生成提示。

# 只有一个输入变量的提示

one_input_prompt = PromptTemplate(input_variables=["adjective"], template="给我讲一个{adjective}段子.")

one_input_prompt.format(adjective="有趣")

输出:'给我讲一个有趣段子.'

# 带有多个输入变量的提示

multiple_input_prompt = PromptTemplate(

    input_variables=["adjective", "content"],

    template="给我讲一个关于{content} {adjective} 段子 ."

)

multiple_input_prompt.format(adjective="恐怖", content="鬼怪")

输出:'给我讲一个关于鬼怪 恐怖 段子 .'

如果您不想手动指定input_variables,您也可以使用from_template类方法创建PromptTemplate。 langchain将根据传递的template自动推断input_variables。

template = "给我讲一个关于{content} {adjective} 段子 ."

prompt_template = PromptTemplate.from_template(template)

prompt_template.input_variables

输出:['adjective', 'content']

给模板变量赋值:

prompt_template.format(adjective="有趣", content="鬼怪")

输出:'给我讲一个关于鬼怪 有趣 段子 .'

2.1.3 模板格式

默认情况下,PromptTemplate 会将提供的模板作为 Python f-string 处理。您可以通过 template_format 参数指定其他模板格式。先安装jinja2包:pip install jinja2

然后执行下面代码:

jinja2_template = "给我讲一个关于{{content}} {{adjective}} 段子"

prompt_template = PromptTemplate.from_template(template=jinja2_template, template_format="jinja2")

prompt_template.format(adjective="有趣", content="鬼怪")

输出:'给我讲一个关于鬼怪 有趣 段子'

2.1.4 将小样本传递给提示模板

few shot examples 是一组示例,可用于帮助语言模型生成更好的响应。相当于微训练,样本越多效果越好。

要使用 few shot examples 生成提示,可以使用 FewShotPromptTemplate。这个类接受一个 PromptTemplate 和一个 few shot examples 列表。然后,它将用 few shot examples 格式化提示模板。

在这个例子中,我们将创建一个提示来生成四字词语的藏头诗。先举几个例子,告诉模型什么叫藏头诗,然后让他仿写。

from langchain import PromptTemplate

from langchain import FewShotPromptTemplate

examples=[

    {

        "输入":"爱我中华",

        "输出":"爱献祖国情义真,我将热血报国恩。中流砥柱英雄志,华夏崛起江山稳。"

    },

    {

        "输入":"情真意切",

        "输出":"情多思远聊开樽,真檀一炷石楼深。意气雄豪非分理,切将浊酒伴清吟。"

    },

    {

        "输入":"新年快乐",

        "输出":"新春梅绽雪飞扬,年味浓浓贺岁忙。快意人生无恨事,乐将喜庆嵌诗行。"

    },

]

example_template="""

输入:{输入}

输出:{输出}

"""

example_prompt=PromptTemplate(

    input_variables=["输入","输出"],

    template=example_template

)

prefix="""

请根据输入的四字词语写四句藏头诗,要保证每句的第一个字连起来读,恰好是输入的四字词语。举例如下:

"""

suffix="""

输入:{query}

输出:

"""

few_shot_prompt_template=FewShotPromptTemplate(

    examples=examples,

    example_prompt=example_prompt,

    prefix=prefix,

    suffix=suffix,

    input_variables=["query"],

    example_separator="\n\n"

)

print(few_shot_prompt_template.format(query="舍我其谁"))

输出:

请根据输入的四字词语写四句藏头诗,要保证每句的第一个字连起来读,恰好是输入的四字词语。举例如下:输入:爱我中华输出:爱献祖国情义真,我将热血报国恩。中流砥柱英雄志,华夏崛起江山稳。输入:情真意切输出:情多思远聊开樽,真檀一炷石楼深。意气雄豪非分理,切将浊酒伴清吟。输入:新年快乐输出:新春梅绽雪飞扬,年味浓浓贺岁忙。快意人生无恨事,乐将喜庆嵌诗行。输入:舍我其谁 输出:

from langchain import LLMChain

llm_chain=LLMChain(

    prompt=few_shot_prompt_template,

    llm=llm

)

query="舍我其谁"

print(llm_chain.run(query))

输出:

舍近求远著文章,我辈逍遥世外源。其乐融融山水美,谁与同谋共家园。

呵呵,第二句怎么八个字,行了ChatGLM也就这样了。

2.2 与聊天相关的提示模板

Chat Models以聊天消息列表作为输入——这个列表通常称为提示。这些聊天消息与原始字符串(您将传递给LLM模型的字符串)不同,因为每个消息都与一个角色相关联。

例如,在OpenAI的Chat Completion API(opens in a new tab)中,聊天消息可以与AI、人类或系统角色相关联。模型应更密切地遵循系统聊天消息的指示。

因此,LangChain提供了几个相关的提示模板,以便轻松构建和处理提示。在查询聊天模型时,建议您使用这些与聊天相关的提示模板,而不是PromptTemplate,以充分发挥基础聊天模型的潜力。

from langchain.prompts import (

ChatPromptTemplate,

    PromptTemplate,

    SystemMessagePromptTemplate,

    AIMessagePromptTemplate,

    HumanMessagePromptTemplate,

)

from langchain.schema import (

    AIMessage,

    HumanMessage,

    SystemMessage

)

template=" 你是一个把 {input_language} 翻译成 {output_language}的助手。"

system_message_prompt = SystemMessagePromptTemplate.from_template(template)

human_template="{text}"

human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

llm_chain=LLMChain(

    prompt=chat_prompt,

    llm=llm

)

llm_chain.run(text="I love programming",input_language="English",output_language="Chinese")

输出:

'System: 编程是一种我喜欢的工作。'

不同类型的 MessagePromptTemplate LangChain 提供了不同类型的 MessagePromptTemplate。其中最常用的是 AIMessagePromptTemplate、SystemMessagePromptTemplate 和 HumanMessagePromptTemplate,分别用于创建 AI 消息、系统消息和人类消息。但是,在聊天模型支持使用任意角色发送聊天消息。

未完待续。


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容