【LangChain】langchain_core.prompts 模块:结构化的提示模板(Template)列举

LangChain 中支持许多的模板(Template)类型,这些模板用于格式化输入,生成 LLM 可处理的提示文本。

本文基于 LangChain 0.3.x,详细介绍 LangChain 中支持的模板类(主要在 langchain_core.prompts 模块),包括功能、参数和使用场景,并提供一个独立示例,展示如何使用 PromptTemplateChatPromptTemplate 构建一个简单的问答应用,使用 langchain_openai.ChatOpenAI 作为 LLM。


LangChain 中的模板类型

LangChain 的模板类主要位于 langchain_core.prompts 模块,用于创建结构化的提示,动态填充变量以供 LLM 处理。这些模板支持不同的提示格式(如纯文本、聊天消息),适用于各种任务(如问答、对话、RAG)。以下是 LangChain 支持的主要模板类型,基于官方文档(Prompts) 和源码分析。

1. PromptTemplate
  • 描述:生成纯文本提示的模板,适合非聊天模型或简单任务。
  • 模块langchain_core.prompts.PromptTemplate
  • 功能
    • 使用字符串模板,包含占位符(如 {variable})。
    • 支持 f-stringjinja2 格式化。
    • 动态填充变量,生成最终提示。
  • 主要参数
    • template(必填):字符串模板,如 "问题:{question}\n回答:"
    • input_variables(可选):模板中使用的变量列表。
    • template_format(默认 "f-string"):格式化方式("f-string", "jinja2")。
    • partial_variables(可选):预定义的部分变量。
  • 方法
    • format(**kwargs) -> str:生成格式化后的字符串。
    • format_prompt(**kwargs) -> PromptValue:返回 PromptValue 对象(内部用)。
    • partial(**kwargs) -> PromptTemplate:填充部分变量,返回新模板。
  • 使用场景
    • 简单问答或文本生成。
    • 与非聊天 LLM(如 LlamaCpp)结合。
    • 格式化 RAG 系统的上下文。
  • 示例
    from langchain_core.prompts import PromptTemplate
    template = PromptTemplate(
        template="问题:{question}\n回答:",
        input_variables=["question"]
    )
    prompt = template.format(question="什么是人工智能?")
    # 输出: "问题:什么是人工智能?\n回答:"
    
2. ChatPromptTemplate
  • 描述:生成聊天消息列表的模板,适合聊天模型(如 ChatOpenAI)。
  • 模块langchain_core.prompts.ChatPromptTemplate
  • 功能
    • 创建结构化消息(如 SystemMessage, HumanMessage, AIMessage)。
    • 支持 MessagesPlaceholder 动态注入对话历史。
    • 适配聊天模型的输入格式。
  • 主要参数
    • messages(必填):消息模板列表,包含 SystemMessagePromptTemplateHumanMessagePromptTemplate 等。
    • input_variables(可选):模板中使用的变量。
  • 方法
    • format_messages(**kwargs) -> List[BaseMessage]:生成消息列表。
    • format_prompt(**kwargs) -> ChatPromptValue:返回 ChatPromptValue 对象。
    • from_messages(cls, messages) -> ChatPromptTemplate:类方法,从消息列表创建模板。
  • 使用场景
    • 对话系统或 RAG(结合对话历史)。
    • 与聊天模型(如 ChatOpenAI, ChatAnthropic)结合。
    • 需要系统指令或多轮对话。
  • 示例
    from langchain_core.prompts import ChatPromptTemplate
    template = ChatPromptTemplate.from_messages([
        ("system", "你是一个专家,回答问题。"),
        ("human", "问题:{question}")
    ])
    messages = template.format_messages(question="什么是人工智能?")
    # 输出: [SystemMessage(content="你是一个专家..."), HumanMessage(content="问题:什么是人工智能?")]
    
3. SystemMessagePromptTemplate
  • 描述:生成系统消息的模板,通常用于设置 LLM 的角色或行为。
  • 模块langchain_core.prompts.chat.SystemMessagePromptTemplate
  • 功能
    • 创建 SystemMessage,定义对话的上下文或指令。
    • 常用于 ChatPromptTemplate 内。
  • 主要参数
    • promptPromptTemplate 实例,定义系统消息内容。
    • input_variables:变量列表。
  • 使用场景
    • 定义 LLM 的角色(如 “你是一个历史学家”)。
    • 设置对话的全局指令。
  • 示例
    from langchain_core.prompts import SystemMessagePromptTemplate, PromptTemplate
    system_template = SystemMessagePromptTemplate.from_template(
        "你是{role}专家。",
        input_variables=["role"]
    )
    message = system_template.format(role="人工智能")
    # 输出: SystemMessage(content="你是人工智能专家。")
    
4. HumanMessagePromptTemplate
  • 描述:生成用户消息的模板,表示用户输入。
  • 模块langchain_core.prompts.chat.HumanMessagePromptTemplate
  • 功能
    • 创建 HumanMessage,表示用户的问题或输入。
    • 常用于 ChatPromptTemplate 内。
  • 主要参数
    • promptPromptTemplate 实例,定义用户消息内容。
    • input_variables:变量列表。
  • 使用场景
    • 格式化用户问题或指令。
    • 构建多轮对话。
  • 示例
    from langchain_core.prompts import HumanMessagePromptTemplate, PromptTemplate
    human_template = HumanMessagePromptTemplate.from_template(
        "问题:{question}",
        input_variables=["question"]
    )
    message = human_template.format(question="什么是人工智能?")
    # 输出: HumanMessage(content="问题:什么是人工智能?")
    
5. AIMessagePromptTemplate
  • 描述:生成 AI 消息的模板,表示 LLM 的响应(较少直接使用)。
  • 模块langchain_core.prompts.chat.AIMessagePromptTemplate
  • 功能
    • 创建 AIMessage,模拟 LLM 的输出。
    • 通常用于测试或构造对话历史。
  • 主要参数
    • promptPromptTemplate 实例,定义 AI 消息内容。
    • input_variables:变量列表。
  • 使用场景
    • 模拟对话历史。
    • 测试链的行为。
  • 示例
    from langchain_core.prompts import AIMessagePromptTemplate, PromptTemplate
    ai_template = AIMessagePromptTemplate.from_template(
        "回答:{answer}",
        input_variables=["answer"]
    )
    message = ai_template.format(answer="人工智能是...")
    # 输出: AIMessage(content="回答:人工智能是...")
    
6. MessagesPlaceholder
  • 描述:占位符,用于动态注入对话历史或消息列表。
  • 模块langchain_core.prompts.chat.MessagesPlaceholder
  • 功能
    • ChatPromptTemplate 中预留位置,填充 BaseMessage 列表(如对话历史)。
    • 常与 RunnableWithMessageHistory 结合。
  • 主要参数
    • variable_name(必填):占位符名称。
    • optional(默认 False):是否允许空消息列表。
  • 使用场景
    • 管理对话历史(如 ChatMessageHistory)。
    • 构建支持多轮对话的链。
  • 示例
    from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
    template = ChatPromptTemplate.from_messages([
        MessagesPlaceholder(variable_name="chat_history"),
        ("human", "{question}")
    ])
    
7. FewShotPromptTemplate
  • 描述:支持少样本学习(Few-Shot Learning)的模板,提供示例提示。
  • 模块langchain_core.prompts.FewShotPromptTemplate
  • 功能
    • 包含示例(examples)和前缀/后缀模板,生成带示例的提示。
    • 支持动态选择示例(通过 example_selector)。
  • 主要参数
    • examples:示例列表,每个示例是字典。
    • example_promptPromptTemplate,定义示例格式。
    • prefix/suffix:提示的前缀/后缀。
    • input_variables:变量列表。
    • example_selector(可选):动态选择示例的工具。
  • 使用场景
    • 少样本学习,教 LLM 特定任务。
    • 格式化复杂任务(如分类、翻译)。
  • 示例
    from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
    examples = [
        {"question": "什么是太阳?", "answer": "太阳是恒星。"},
        {"question": "什么是月亮?", "answer": "月亮是卫星。"}
    ]
    example_prompt = PromptTemplate(
        template="问题:{question}\n回答:{answer}\n",
        input_variables=["question", "answer"]
    )
    template = FewShotPromptTemplate(
        examples=examples,
        example_prompt=example_prompt,
        prefix="你是一个天文学家,回答问题:",
        suffix="问题:{question}\n回答:",
        input_variables=["question"]
    )
    prompt = template.format(question="什么是星星?")
    # 输出: 你是一个天文学家,回答问题:
    # 问题:什么是太阳?
    # 回答:太阳是恒星。
    # 问题:什么是月亮?
    # 回答:月亮是卫星。
    # 问题:什么是星星?
    # 回答:
    
8. FewShotChatPromptTemplate
  • 描述:支持少样本学习的聊天模板,生成消息列表。
  • 模块langchain_core.prompts.FewShotChatPromptTemplate
  • 功能
    • 类似 FewShotPromptTemplate,但生成 SystemMessage/HumanMessage 等。
    • 适合聊天模型的少样本任务。
  • 主要参数
    • examples:示例列表。
    • example_promptChatPromptTemplate,定义示例格式。
    • input_variables:变量列表。
  • 使用场景
    • 聊天模型的少样本学习。
    • 复杂对话任务。
  • 示例
    from langchain_core.prompts import FewShotChatPromptTemplate, ChatPromptTemplate
    examples = [
        {"input": "什么是太阳?", "output": "太阳是恒星。"}
    ]
    example_prompt = ChatPromptTemplate.from_messages([
        ("human", "{input}"),
        ("ai", "{output}")
    ])
    template = FewShotChatPromptTemplate(
        examples=examples,
        example_prompt=example_prompt,
        input_variables=["question"]
    )
    
9. PipelinePromptTemplate
  • 描述:组合多个模板,生成复杂的提示。
  • 模块langchain_core.prompts.PipelinePromptTemplate
  • 功能
    • 将子模板(如 PromptTemplate)组合成最终提示。
    • 支持嵌套和依赖关系。
  • 主要参数
    • final_prompt:最终的 PromptTemplate
    • pipeline_prompts:子模板列表,每个元素是 (name, PromptTemplate)
  • 使用场景
    • 复杂任务,需多个提示阶段。
    • 动态组合上下文和指令。
  • 示例
    from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate
    final_template = PromptTemplate.from_template("{intro}\n{question}")
    intro_template = PromptTemplate.from_template("你是一个专家。")
    pipeline = PipelinePromptTemplate(
        final_prompt=final_template,
        pipeline_prompts=[("intro", intro_template), ("question", PromptTemplate.from_template("问题:{q}"))]
    )
    prompt = pipeline.format(q="什么是人工智能?")
    # 输出: 你是一个专家。
    # 问题:什么是人工智能?
    
模板类型总结
模板类模块输出类型主要场景
PromptTemplatelangchain_core.prompts纯文本简单问答、RAG、非聊天模型
ChatPromptTemplatelangchain_core.prompts消息列表对话、聊天模型、RAG
SystemMessagePromptTemplatelangchain_core.prompts.chatSystemMessage设置角色、指令
HumanMessagePromptTemplatelangchain_core.prompts.chatHumanMessage用户输入
AIMessagePromptTemplatelangchain_core.prompts.chatAIMessage模拟 AI 响应
MessagesPlaceholderlangchain_core.prompts.chat消息占位符对话历史
FewShotPromptTemplatelangchain_core.prompts纯文本少样本学习
FewShotChatPromptTemplatelangchain_core.prompts消息列表聊天模型少样本学习
PipelinePromptTemplatelangchain_core.prompts纯文本复杂提示组合

推荐模板

  • 简单任务PromptTemplate(纯文本,易用)。
  • 对话系统ChatPromptTemplate(支持聊天模型和历史)。
  • 复杂任务FewShotPromptTemplatePipelinePromptTemplate

使用模板的问答示例

以下是一个独立示例,展示如何使用 PromptTemplateChatPromptTemplate,结合 langchain_openai.ChatOpenAI 构建一个简单的问答应用,回答关于机器学习的问题。

代码

import os
os.environ["OPENAI_API_KEY"] = "Your OpenAI API Key"

from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate, ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough

# 初始化 ChatOpenAI LLM
llm = ChatOpenAI(temperature=0, model="gpt-4")

# 定义 PromptTemplate(纯文本)
text_prompt = PromptTemplate(
    template="""你是一个机器学习专家,回答以下问题:
问题:{question}
回答:""",
    input_variables=["question"]
)

# 定义 ChatPromptTemplate(消息列表)
chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个机器学习专家,简洁回答问题。"),
    ("human", "{question}")
])

# 创建问答链(使用 ChatPromptTemplate)
qa_chain = (
    {"question": RunnablePassthrough()}
    | chat_prompt
    | llm
    | StrOutputParser()
)

# 调用链
print("问答链输出:")
response = qa_chain.invoke("什么是机器学习?")
print(response)
response = qa_chain.invoke("它的主要类型有哪些?")
print(response)

输出示例

问答链输出:
机器学习是人工智能的分支,通过数据训练模型以进行预测或决策。
机器学习的主要类型包括监督学习、无监督学习和强化学习。
代码说明
  1. 模板使用
    • PromptTemplate:定义纯文本提示(未直接使用,仅展示)。
    • ChatPromptTemplate:生成消息列表,包含系统指令和用户问题,适合 ChatOpenAI
  2. LLM
    • ChatOpenAIgpt-4)生成高质量答案。
  3. 问答链
    • LCEL 链组合 chat_promptllmStrOutputParser
    • RunnablePassthrough 传递输入问题。
  4. 主题
    • 示例聚焦机器学习问答,简单且独立。
  5. 独立性
    • 不涉及向量存储、RAG 或之前的 Milvus、LlamaCpp 内容。

运行要求

  • OpenAI API 密钥有效。
  • 安装依赖:
    pip install --upgrade langchain langchain-core langchain-openai
    

注意事项

  1. API 密钥
    • 使用 .env 文件:
      from dotenv import load_dotenv
      load_dotenv()
      
    • 确保密钥支持 gpt-4
  2. 依赖
    • 安装:
      pip install --upgrade langchain langchain-core langchain-openai
      
  3. 模板选择
    • 聊天模型:优先使用 ChatPromptTemplate,支持消息格式。
    • 非聊天模型:使用 PromptTemplate,如结合 LlamaCpp
    • 对话历史:添加 MessagesPlaceholder
  4. 性能优化
    • 模板
      • 确保 input_variables 与占位符一致。
      • 使用简洁模板,减少 LLM 处理负担。
    • LLM
      • 调整 temperature(如 0.5)控制随机性。
      • 设置 max_tokens(如 512)限制输出长度。
  5. 错误调试
    • 变量缺失
      • 检查 formatformat_messages 的输入:
        prompt.format(question="测试")  # 确保所有变量提供
        
    • 输出格式
      • 使用 StrOutputParser 确保纯文本输出。
      • 若需 JSON,改用 JsonOutputParser
        from langchain_core.output_parsers import JsonOutputParser
        

常见问题

Q1:如何选择合适的模板?
A:

  • 简单问答PromptTemplate(纯文本,易用)。
  • 对话系统ChatPromptTemplate(支持消息和历史)。
  • 少样本学习FewShotPromptTemplateFewShotChatPromptTemplate
  • 复杂提示PipelinePromptTemplate

Q2:如何添加对话历史?
A:使用 ChatPromptTemplate 结合 MessagesPlaceholderRunnableWithMessageHistory

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
prompt = ChatPromptTemplate.from_messages([
    MessagesPlaceholder(variable_name="chat_history"),
    ("human", "{question}")
])
chain = prompt | llm | StrOutputParser()
chain_with_history = RunnableWithMessageHistory(
    chain,
    lambda session_id: ChatMessageHistory(),
    input_messages_key="question",
    history_messages_key="chat_history"
)

Q3:可以结合 RAG 吗?
A:可以,使用 PromptTemplateChatPromptTemplate 包含上下文:

prompt = ChatPromptTemplate.from_messages([
    ("system", "根据上下文回答:{context}"),
    ("human", "{question}")
])

Q4:支持其他模板格式吗?
A:支持 jinja2(需安装 jinja2):

prompt = PromptTemplate(
    template="Question: {{ question }}\nAnswer:",
    input_variables=["question"],
    template_format="jinja2"
)

总结

LangChain 的模板类(在 langchain_core.prompts)包括:

  • PromptTemplate:纯文本提示,适合简单任务。
  • ChatPromptTemplate:消息列表,适合聊天模型。
  • SystemMessagePromptTemplate/HumanMessagePromptTemplate/AIMessagePromptTemplate:消息类型,构建对话。
  • MessagesPlaceholder:动态历史注入。
  • FewShotPromptTemplate/FewShotChatPromptTemplate:少样本学习。
  • PipelinePromptTemplate:复杂提示组合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彬彬侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值