☰
【Agent】LangChain核心组件--提示词模板
2026/10/24 2:30:29 网站建设 项目流程

1.1 概念

提示词模板(Prompt Template)是 LangChain 的核心抽象之一,它被广泛应用于构建大语言模型(LLM)应用的各个环节。

简单来说,只要是需要动态、批量、或有结构地向大语言模型【发送请求】的地方,几乎都会用到提示词模板。

一个简单的例子,假设我们想根据一个城市名询问 LLM 其历史,按照之前的做法,我们可以定义HumanMessage("请介绍上海的历史")、HumanMessage("请介绍西安的历史")消息等等。可以发现每次询问都会描写重复的消息内容: 请介绍xxx的历史 。

在 LangChain 中,针对这种情况,可以定义一个模板:

  • 固定文本(模板):"请介绍{city}的历史。"
  • 输入变量:["city"]

定义好后,可以使用该模板:

  • 当我们需要查询北京时,就将 city 变量赋值为 “北京”。模板引擎会生成:"请介绍北京的历史。"
  • 当我们需要查询上海时,就将 city 变量赋值为 “上海”。模板引擎会生成:"请介绍上海的历史。"

由此可得:提示词模板就是一个可复用的提示词蓝图,它允许我们动态地生成提示词,而不是每次都手动编写完整的提示词。它类似于编程中的字符串格式化功能。你创建一个带有“占位符”的模板,然后在运行时,用具体的值(变量)填充这些占位符,从而生成一个最终发送给 LLM 的完整提示词。

提示词模板解决了以下几个核心问题:

  1. 可复用性: 只需定义一个模板,就可以用于无数个类似的查询。
  2. 关注点分离: 将提示词的结构和逻辑(工程)与具体的内容和数据分离开。提示工程师可以专注于优化模板,而应用程序则负责提供变量值。
  3. 一致性: 确保发送给LLM的提示词结构统一,这有助于获得更稳定、可预测的输出结果。
  4. 可维护性: 如果需要修改提示词的风格或结构,只需修改一个模板文件,而不用在代码的无数个地方进行修改。

1.2 用法

1.2.1 字符串模板

LangChain 提供了PromptTemplate类来轻松实现这一功能。PromptTemplate实现了标准的 Runnable 接口。示例如下:

fromlangchain_core.promptsimportPromptTemplate# 1. 定义模板prompt_template=PromptTemplate.from_template("Translate the following into {language}")# 2. 实例化模板print(prompt_template.invoke({"language":"Chinese"}))

打印结果:

text='Translate the following into Chinese'

说明:
class langchain_core.prompts.prompt.PromptTemplate类,其参数如下:

  • template:提示模板
  • input_variables:需要其值作为提示输入的变量的名称列表。

内置方法:
from_template():从模板定义提示模板。方法返回了一个 PromptTemplate 实例

因此除了上面示例中PromptTemplate.from_template定义提示模板的方式外,下面这种方法也可以直接初始化模板:

prompt_template=PromptTemplate(input_variables=["language"],template="Translate the following into {language}",)

1.2.2 聊天消息模板

ChatPromptTemplate模板:专为 LangChain 聊天模型设计。可以方便地构建包含SystemMessage、HumanMessage、AIMessage的消息模板。如下代码所示:

fromlangchain_core.promptsimportChatPromptTemplate# 1. 设置模板prompt_template=ChatPromptTemplate([("system","Translate the following into {language}."),("user","{text}")])# 说明:# 在 0.2.24 版本后可以直接使用ChatPromptTemplate()来初始化模板# 在 0.2.24 版本前,需要使用 ChatPromptTemplate.from_messages()来初始化模板# 2. 实例化模板,获取消息实例messagesValue=prompt_template.invoke({"language":"Chinese","text":"what is your name?"})messages=messagesValue.to_messages()print(messages)

打印结果:

[ SystemMessage(content='Translate the following into Chinese.', additional_kwargs={}, response_metadata={}), HumanMessage(content='what is your name?', additional_kwargs={}, response_metadata={}) ]

现在,我们可以将该结果发送给任何一个 LLM 来获取答案。如下所示:

fromlangchain_openaiimportChatOpenAIfromlangchain_core.promptsimportChatPromptTemplatefromlangchain_core.output_parsersimportStrOutputParser# 定义大模型model=ChatOpenAI(model="gpt-4o-mini")# 1. 设置模板prompt_template=ChatPromptTemplate([("system","Translate the following into {language}."),("user","{text}")])# 2. 实例化模板,获取消息实例messagesValue=prompt_template.invoke({"language":"Chinese","text":"what is your name?"})messages=messagesValue.to_messages()print(messages)# 3. 输出解析parser=StrOutputParser()chain=model|parserprint(chain.invoke(messages))

打印结果:

你的名字是什么?

由于ChatPromptTemplate同样也实现了标准的 Runnable 接口,因此我们还可以通过链来完成调用。如下所示:

fromlangchain_openaiimportChatOpenAIfromlangchain_core.promptsimportChatPromptTemplatefromlangchain_core.output_parsersimportStrOutputParser# 定义大模型model=ChatOpenAI(model="gpt-4o-mini")# 1. 设置模板prompt_template=ChatPromptTemplate([("system","Translate the following into {language}."),("user","{text}")])# 2. 定义输出解析器parser=StrOutputParser()# 3. 定义链chain=prompt_template|model|parserfortokeninchain.stream({"language":"English","text":"你好,我叫斯蒂芬,很高兴认识你"}):print(token,end="|")

打印结果:

|Hello|,| my| name| is| Stephen|,| nice| to| meet| you|.||

1.2.3 消息占位符

在上面的ChatPromptTemplate中,我们看到了如何格式化两条消息,每条消息都是一个字符串。但如果我们希望将消息插入特定位置怎么办?使用MessagesPlaceholder。

MessagesPlaceholder负责在特定位置添加消息列表。代码如下:

fromlangchain_core.promptsimportChatPromptTemplate,MessagesPlaceholderfromlangchain_core.messagesimportHumanMessage,AIMessage prompt_template=ChatPromptTemplate([("system","你是一个聊天助手"),MessagesPlaceholder("msgs")# 消息占位符])messages_to_pass=[HumanMessage(content="中国首都是哪里?"),AIMessage(content="中国首都是北京。"),HumanMessage(content="那法国呢?")]formatted_prompt=prompt_template.invoke({"msgs":messages_to_pass})print(formatted_prompt)

打印结果:

messages=[ SystemMessage(content='你是一个聊天助手', additional_kwargs={}, response_metadata={}), HumanMessage(content='中国首都是哪里?', additional_kwargs={}, response_metadata={}), AIMessage(content='中国首都是北京。'), HumanMessage(content='那法国呢?', additional_kwargs={}, response_metadata={}) ]

在不显式使用MessagesPlaceholder类也可以完成该能力:

fromlangchain_core.promptsimportChatPromptTemplatefromlangchain_core.messagesimportHumanMessage,AIMessage prompt_template=ChatPromptTemplate([("system","You are a helpful assistant"),("placeholder","{msgs}")])messages_to_pass=[HumanMessage(content="中国首都是哪里?"),AIMessage(content="中国首都是北京。"),HumanMessage(content="那法国呢?")]formatted_prompt=prompt_template.invoke({"msgs":messages_to_pass})print(formatted_prompt)

1.3 使用 LangChain Hub 的提示词模板

LangChain Hub 是一个用于上传、浏览、拉取和管理提示词(prompts)的地方。

随着 LLM 的发展,提示变得越来越重要。LangChain 正在打造一个与像 GitHub 这样的传统平台,GitHub长期以来一直是共享和协作代码的首选平台。于是推出了 LangChain Hub 平台。

LangChain Hub 创建一个分享和发现 Prompt 的平台,使得开发者可以更容易地发现新用例和精炼提示。 这一举措使提示工程师更容易合作,重复使用现有的提示,并对其进行微调以实现特定的结果,从而加速对话代理和其他基于语言的应用程序的开发和部署。早期的时候 LangChain Hub 有 Prompt、Chain、Agent,现在只有Prompt。

LangChain Hub 官网地址:https://smith.langchain.com/hub/。通过登录到 Hub 来探索所有现有提示

目前收藏最高的提示词模板是:hardkothari/prompt-maker。我们就以它为示例,演示一下如何使用 LangChain Hub 上的提示。

Prompt Maker 模板是一个【提示生成器】 ,它可以自动化优化提示的过程,从而提高语言模型在各种应用中的质量和效果。

要想使用该能力,需要先申请并配置 LangSmith 环境变量:LANGSMITH_API_KEY="你的LangSmith API Key"。接着,需要从 hub 拉取相应的提示,并使用,代码如下:

fromlangchain_openaiimportChatOpenAIfromlangsmithimportClient# 从 hub 拉取 "hardkothari/prompt-maker" 提示词模板。client=Client()prompt=client.pull_prompt("hardkothari/prompt-maker",include_model=True)# 定义模型model=ChatOpenAI(model="gpt-4o-mini")# 定义链chain=prompt|modelwhileTrue:task=input("\n你的任务是什么?(输入 quit 退出聊天)\n")iftask=='quit':breaklazy_prompt=input("\n你当前的提示是什么?(输入 quit 退出聊天)\n")iflazy_prompt=='quit':breakprint("\n Response:")chain.invoke({'lazy_prompt':lazy_prompt,'task':task}).pretty_print()

运行代码:

你的任务是什么?(输入 quit 退出聊天) 写一个快排代码 你当前的提示是什么?(输入 quit 退出聊天) 开发专家,需中文回复 Response: ================================== Ai Message ================================== As a coding expert specialized in algorithms and data structures, please write a detailed implementation of the Quick Sort algorithm in Python. ### Instructions: Your code should be well-structured, with clear comments explaining each step of the algorithm. Additionally, include an example of how to use the function to sort a list of integers and print the sorted result. ### Context: The implementation should focus on efficiency and clarity, ideally spanning no more than 20 lines of code. Ensure that the prompt is in Chinese, and structure your response to be easily understandable for readers with a basic knowledge of programming. Example: ```python def quick_sort(arr): # 快速排序函数实现 ... return sorted_arr # 使用示例 unsorted_list = [34, 7, 23, 32, 5, 62] print(quick_sort(unsorted_list)) Please provide the complete code and any additional notes that could aid in understanding the Quick Sort algorithm. Thank you!

通过使用这个模板,可以大大减少手动调整提示所需的工作量,从而节省时间和资源。Prompt Maker 通过分析初始提示的结构和内容,然后应用一组预定规则或算法来优化提示,以提高响应质量、清晰度和相关性。这在提示的质量对模型的输出有很大影响的场景中特别有用,比如客户服务机器人、对话代理或数据分析任务。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询