Langchain的提示词模板

        因为做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",
    "input_variables": [
      "ai_name",
      "ai_role",
      "instructions"
    ],
    "template_path": "template.txt"
}


template.py的代码如下:

# coding: utf-8
from langchain_core.prompts.loading import load_prompt
from langchain_core.prompts.pipeline import PipelinePromptTemplate
from langchain_core.prompts.prompt import PromptTemplate

# 第一种情况:直接处理字符串模板
simple_template = "这个是一个最简单的大语言模型的模板,请回答:{question}"
simple_prompt = PromptTemplate.from_template(simple_template)
prompt = simple_prompt.format(question="程序员节是哪一天?")
print(f"^^^^^^^\n{prompt}\n^^^^^^^")
# 会输出如下信息:
"""
^^^^^^^
这个是一个最简单的大语言模型的模板,请回答:程序员节是哪一天?
^^^^^^^
"""

# 第二种情况:读取文件。load_prompt 返回的是 BasePromptTemplate
main_prompt_template = load_prompt("template.json")
# print(main_prompt_template)

partial_variables = {}
partial_variables["instructions"] = "按照给定的思路和上下文,回答问题。"

# 将有值的变量填充到模板中
main_prompt_template = main_prompt_template.partial(**partial_variables)
# print(main_prompt_template)

# 设置模板中的其它变量
prompt = main_prompt_template.format(
        ai_name="胖胖",
        ai_role="智能助手机器人"
    )
print(f"******\n{prompt}\n******")
# 会输出:
"""
******
这是一个测试用的模板文件,用于测试模板引擎的功能。
你叫做胖胖,你是智能助手机器人,

按照给定的思路和上下文,回答问题。
******
"""

# 第三种情况:使用PipelinePromptTemplate,可以将多个模板组合在一起
templates = []
task_template = """{task_description}"""

task_prompt = PromptTemplate.from_template(task_template)
templates.append(("task",task_prompt))
print(f"task:{task_prompt.input_variables}")

resources_template = """{support_resources}"""

resources_prompt = PromptTemplate.from_template(resources_template)
templates.append(("resources", resources_prompt))
print(f"resources:{resources_prompt.input_variables}")

final_template = """你的任务是:{task}
你可以使用的资源包括:{resources}
"""

final_prompt = PromptTemplate.from_template(final_template)
pipeline_prompt = PipelinePromptTemplate(
                final_prompt=final_prompt,
                pipeline_prompts=templates
            )
print(f"pipeline: {pipeline_prompt.input_variables}")

pipeline_prompt = pipeline_prompt.format(
        task_description="8月份的销售额是多少",
        support_resources="1. 你可以查阅本地文件列表。2. 你可以读取本地文件。"
    )

print(f"======\n{pipeline_prompt}\n======")
# 会输出:
"""
======
你的任务是:8月份的销售额是多少
你可以使用的资源包括:1. 你可以查阅本地文件列表。2. 你可以读取本地文件。

======
"""

执行:python template.py

### 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、付费专栏及课程。

余额充值