Langchain的提示词模板

文章介绍了在AI项目中如何使用Langchain的提示词模板处理固定和可变文本,包括BasePromptTemplate和PromptTemplate的使用方法,以及通过file和template创建和填充模板的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        因为做AI项目的过程中,需要处理各种提示词(prompt),其中有些是固定的文本,有些是会反复修改的。如果是简单的提示词,直接用python里面的字符串format()或者replace()函数进行处理即可。对于复杂的,还是用langchain里面的提示词模板更方便。

        为了方便处理llm的promt,langchain提供了提示词模板。具体文档参见官方文档:https://api.python.langchain.com/en/latest/core_api_reference.html#module-langchain_core.prompts

        常见的类有BasePromptTemplate、PipelinePromptTemplate和PromptTemplate。其中BasePromptTemplate是后面2个类的基类(PromptTemplate的直接父类是StringPromptTemplate,而StringPromptTemplate的直接父类则是BasePromptTemplate)。


BasePromptTemplate中常用的方法有format(),input_variables(),partial(),save()。

PromptTemplate中常用的方法有from_file()、from_template()。

具体使用请参见下面的源码:template.txt文件中的内容如下:

这是一个测试用的模板文件,用于测试模板引擎的功能。
你叫做{ai_name},你是{ai_role},

{instructions}


template.json中的文件内容如下:

{
    "_type": "prompt",
   
### LangChain Prompt Templates 的概述 LangChain 是一种用于构建语言模型应用程序的强大框架,其中 `Prompt Templates` 起到了核心作用。以下是关于 LangChain 中提示模板的相关介绍: #### 1. **String PromptTemplates** 这是最基础的一种提示模板形式,适用于简单的字符串操作场景。它允许开发者定义一个固定的字符串结构,并通过变量填充动态内容。 示例代码如下: ```python from langchain import PromptTemplate template = "What is a good name for a company that makes {product}?" prompt = PromptTemplate(input_variables=["product"], template=template) formatted_prompt = prompt.format(product="colorful socks") print(formatted_prompt) ``` 上述代码展示了如何利用 String PromptTemplates 创建并格式化提示语句[^1]。 --- #### 2. **ChatPromptTemplates** 这种类型的提示模板专为对话型应用设计,支持多轮交互以及复杂的消息处理逻辑。它可以组合多个消息组件(如人类提问、AI回复等),从而实现更自然流畅的对话体验。 下面是一个 ChatPromptTemplates 使用的例子: ```python from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, ) system_template = "You are Qwen, an AI assistant who follows instructions extremely well." human_template = "{question}" ai_template = "The answer to your question is..." system_message_prompt = SystemMessagePromptTemplate.from_template(system_template) human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) ai_message_prompt = AIMessagePromptTemplate.from_template(ai_template) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt, ai_message_prompt]) messages = chat_prompt.format_messages(question="How do I optimize my website?") for message in messages: print(message.content) ``` 此代码片段说明了如何配置系统角色、用户输入及 AI 输出的内容结构。 --- #### 3. **Few-Shot Learning with Examples** 为了进一步提升大语言模型的表现能力,“少样本学习”成为了一种常用策略。“Few-shot learning”的基本思路是在实际请求之前向模型展示若干示范案例,帮助其理解任务需求。 例如,当希望让模型生成特定风格的文章摘要时,可以通过以下方式设置 few-shot 提示模板: ```python from langchain.prompts.example_selector import LengthBasedExampleSelector from langchain.prompts.prompt import PromptTemplate from langchain.prompts.few_shot import FewShotPromptTemplate examples = [ {"input": "Apple", "output": "A fruit"}, {"input": "Carrot", "output": "A vegetable"} ] example_formatter_template = """Input: {input}\nOutput: {output}""" example_prompt = PromptTemplate( input_variables=["input", "output"], template=example_formatter_template ) dynamic_example_selector = LengthBasedExampleSelector(examples=examples, example_prompt=example_prompt, max_length=50) few_shot_prompt = FewShotPromptTemplate( example_selector=dynamic_example_selector, example_prompt=example_prompt, prefix="Classify the following items into categories.", suffix="\n\nInput: {new_input}\nOutput:", input_variables=["new_input"] ) final_prompt = few_shot_prompt.format(new_input="Banana") print(final_prompt) ``` 以上脚本演示了如何基于长度筛选合适的样例集合,并将其嵌入到最终提交给模型的任务描述之中[^3]。 --- #### 4. **自定义与扩展** 除了内置的标准功能外,LangChain 还提供了高度可定制化的接口,使得开发人员能够针对具体业务场景调整优化提示机制。比如引入外部数据源作为上下文补充材料;或者结合条件分支判断逻辑增强灵活性等等[^2]。 --- ### 总结 通过对 LangChain 提示模板的学习与实践,不仅可以简化日常工作中涉及的人工干预环节,而且有助于挖掘更大潜力释放出来的大规模预训练模型价值所在。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值