
1.1 概念提示词模板Prompt Template是 LangChain 的核心抽象之一它被广泛应用于构建大语言模型LLM应用的各个环节。简单来说只要是需要动态、批量、或有结构地向大语言模型【发送请求】的地方几乎都会用到提示词模板。一个简单的例子假设我们想根据一个城市名询问 LLM 其历史按照之前的做法我们可以定义HumanMessage(请介绍上海的历史)、HumanMessage(请介绍西安的历史)消息等等。可以发现每次询问都会描写重复的消息内容 请介绍xxx的历史 。在 LangChain 中针对这种情况可以定义一个模板固定文本模板请介绍{city}的历史。输入变量[city]定义好后可以使用该模板当我们需要查询北京时就将 city 变量赋值为 “北京”。模板引擎会生成请介绍北京的历史。当我们需要查询上海时就将 city 变量赋值为 “上海”。模板引擎会生成请介绍上海的历史。由此可得提示词模板就是一个可复用的提示词蓝图它允许我们动态地生成提示词而不是每次都手动编写完整的提示词。它类似于编程中的字符串格式化功能。你创建一个带有“占位符”的模板然后在运行时用具体的值变量填充这些占位符从而生成一个最终发送给 LLM 的完整提示词。提示词模板解决了以下几个核心问题可复用性 只需定义一个模板就可以用于无数个类似的查询。关注点分离 将提示词的结构和逻辑工程与具体的内容和数据分离开。提示工程师可以专注于优化模板而应用程序则负责提供变量值。一致性 确保发送给LLM的提示词结构统一这有助于获得更稳定、可预测的输出结果。可维护性 如果需要修改提示词的风格或结构只需修改一个模板文件而不用在代码的无数个地方进行修改。1.2 用法1.2.1 字符串模板LangChain 提供了PromptTemplate类来轻松实现这一功能。PromptTemplate实现了标准的 Runnable 接口。示例如下fromlangchain_core.promptsimportPromptTemplate# 1. 定义模板prompt_templatePromptTemplate.from_template(Translate the following into {language})# 2. 实例化模板print(prompt_template.invoke({language:Chinese}))打印结果textTranslate the following into Chinese说明class langchain_core.prompts.prompt.PromptTemplate类其参数如下template提示模板input_variables需要其值作为提示输入的变量的名称列表。内置方法from_template()从模板定义提示模板。方法返回了一个 PromptTemplate 实例因此除了上面示例中PromptTemplate.from_template定义提示模板的方式外下面这种方法也可以直接初始化模板prompt_templatePromptTemplate(input_variables[language],templateTranslate the following into {language},)1.2.2 聊天消息模板ChatPromptTemplate模板专为 LangChain 聊天模型设计。可以方便地构建包含SystemMessage、HumanMessage、AIMessage的消息模板。如下代码所示fromlangchain_core.promptsimportChatPromptTemplate# 1. 设置模板prompt_templateChatPromptTemplate([(system,Translate the following into {language}.),(user,{text})])# 说明# 在 0.2.24 版本后可以直接使用ChatPromptTemplate()来初始化模板# 在 0.2.24 版本前需要使用 ChatPromptTemplate.from_messages()来初始化模板# 2. 实例化模板获取消息实例messagesValueprompt_template.invoke({language:Chinese,text:what is your name?})messagesmessagesValue.to_messages()print(messages)打印结果[ SystemMessage(contentTranslate the following into Chinese., additional_kwargs{}, response_metadata{}), HumanMessage(contentwhat is your name?, additional_kwargs{}, response_metadata{}) ]现在我们可以将该结果发送给任何一个 LLM 来获取答案。如下所示fromlangchain_openaiimportChatOpenAIfromlangchain_core.promptsimportChatPromptTemplatefromlangchain_core.output_parsersimportStrOutputParser# 定义大模型modelChatOpenAI(modelgpt-4o-mini)# 1. 设置模板prompt_templateChatPromptTemplate([(system,Translate the following into {language}.),(user,{text})])# 2. 实例化模板获取消息实例messagesValueprompt_template.invoke({language:Chinese,text:what is your name?})messagesmessagesValue.to_messages()print(messages)# 3. 输出解析parserStrOutputParser()chainmodel|parserprint(chain.invoke(messages))打印结果你的名字是什么由于ChatPromptTemplate同样也实现了标准的 Runnable 接口因此我们还可以通过链来完成调用。如下所示fromlangchain_openaiimportChatOpenAIfromlangchain_core.promptsimportChatPromptTemplatefromlangchain_core.output_parsersimportStrOutputParser# 定义大模型modelChatOpenAI(modelgpt-4o-mini)# 1. 设置模板prompt_templateChatPromptTemplate([(system,Translate the following into {language}.),(user,{text})])# 2. 定义输出解析器parserStrOutputParser()# 3. 定义链chainprompt_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_templateChatPromptTemplate([(system,你是一个聊天助手),MessagesPlaceholder(msgs)# 消息占位符])messages_to_pass[HumanMessage(content中国首都是哪里?),AIMessage(content中国首都是北京。),HumanMessage(content那法国呢?)]formatted_promptprompt_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_templateChatPromptTemplate([(system,You are a helpful assistant),(placeholder,{msgs})])messages_to_pass[HumanMessage(content中国首都是哪里?),AIMessage(content中国首都是北京。),HumanMessage(content那法国呢?)]formatted_promptprompt_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 提示词模板。clientClient()promptclient.pull_prompt(hardkothari/prompt-maker,include_modelTrue)# 定义模型modelChatOpenAI(modelgpt-4o-mini)# 定义链chainprompt|modelwhileTrue:taskinput(\n你的任务是什么输入 quit 退出聊天\n)iftaskquit:breaklazy_promptinput(\n你当前的提示是什么输入 quit 退出聊天\n)iflazy_promptquit: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 通过分析初始提示的结构和内容然后应用一组预定规则或算法来优化提示以提高响应质量、清晰度和相关性。这在提示的质量对模型的输出有很大影响的场景中特别有用比如客户服务机器人、对话代理或数据分析任务。