从零起步:LangChain ChatPromptTemplate基础使用

在上篇文章中,我们已经学习PromptTemplate。现在,我们继续学习ChatPromptTemplate。ChatPromptTemplate 是 LangChain 框架中用于构建对话提示的强大工具 。它专为多轮对话场景设计,能将不同角色的消息整合为连贯提示,助力开发者精准引导语言模型生成符合预期的回复。通过定义角色、消息内容及灵活的模板变量,ChatPromptTemplate让创建复杂对话提示变得轻松,无论是构建智能客服、聊天机器人,还是交互式智能助手,都能大幅提升对话交互的逻辑性与流畅性 。
ChatPromptTemplate

1. 基本用途

**ChatPromptTemplate**为聊天式交互场景设计,用于构建多轮对话形式的提示信息。它可以处理不同角色(如人类、AI)的消息,并按照一定的格式组合这些消息。这更符合聊天机器人、对话式 AI 等应用的需求。ChatPromptTemplate能够处理不同角色,是与PromptTemplate最大的不同。

2.模板结构

**ChatPromptTemplate**由多个消息模板组成,每个消息模板对应一个特定的角色(如 HumanMessagePromptTemplateAIMessagePromptTemplate 等)。这些消息模板可以包含各自的占位符,用于填充动态内容。例如:

from langchain.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate
)

# 定义系统消息模板
system_template = "你是一个乐于助人的助手,总是用简洁的语言回答问题。"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

# 定义用户消息模板
human_template = "请提供关于{topic}的简要信息。"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

# 组合成聊天提示模板
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

# 构建提示,填充占位符
prompt = chat_prompt.format_prompt(topic="LLM").to_messages()

print(prompt)
主要参数
  • **messages**:列表类型。定义聊天消息的结构。列表中的每个元素代表一条消息,消息通常由 BaseMessagePromptTemplate 类的实例组成,比如 SystemMessagePromptTemplateHumanMessagePromptTemplate 等,分别对应系统消息、人类消息等不同角色的消息模板。通过 messages 参数可以构建出一个完整的聊天对话流程的提示模板。
  • **input_variables**:列表类型。模板字符串里所有占位符的名称。
  • <font style="color:rgba(0, 0, 0, 0.85);">partial_variables :字典值。键为变量名,值为对应的变量值。通过预先设置部分变量,可以简化后续调用 formatformat_prompt 方法时的输入。
LLM的角色
  • system“角色,通过分配特定行为给聊天助手来创建对话的上下文或范围。例如,如果您希望与ChatGPT在与体育相关的话题范围内进行对话,可以将”system"角色分配给聊天助手,并设置内容为"体育专家”。然后ChatGPT会表现得像体育专家一样回答您的问题。
  • "human"角色,代表实际的最终用户,他向ChatGPT发送提问。
  • "ai“角色,代表响应最终用户提示的实体。这个角色表示消息是助手(聊天模型)的响应。”ai"角色用于在当前请求中设置模型的先前响应,以保持对话的连贯性。

3. 输出格式

**ChatPromptTemplate**:调用 format_messages 方法后,输出的是一个消息列表,列表中的每个元素代表特定角色消息的对象。例如:

messages = chat_prompt.format_messages(topic="LLM")

# 打印生成的消息
for message in messages:
    if isinstance(message, SystemMessage):
        print(f"System: {message.content}")
    elif isinstance(message, HumanMessage):
        print(f"Human: {message.content}")

4. 使用场景

**ChatPromptTemplate**:适合交互式对话应用,如聊天机器人、智能客服等,这些应用需要处理用户和LLM之间的多轮对话。

5. 示例代码

ChatPromptTemplate 示例
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_ollama import ChatOllama

system_template = "你是一位助手,回复信息时语气偏向口语化。"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

human_template = "介绍关于{topic}的一个核心知识点。"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 创建 ChatPromptTemplate 实例
chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt, system_message_prompt])

# 填充模板
messages = chat_prompt.format_messages(topic="LLM")

# 打印生成的消息
for message in messages:
    if isinstance(message, SystemMessage):
        print(f"System: {message.content}")
    elif isinstance(message, HumanMessage):
        print(f"Human: {message.content}")

# 调用模型
model = ChatOllama(model="qwen2.5:3b")
result = model(messages)
print(result.content)

示例2:通过few-shot。对LLM的回复进行规范。

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_ollama import ChatOllama
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages(
      [
         ("system", "你是一位IT技术专家。回答问题时准确且简洁。"),
         MessagesPlaceholder("history"),
         ("human", "{question}")
      ]
)

model = ChatOllama(model="qwen2.5:3b")
chain = prompt|model|StrOutputParser()
response = chain.invoke({
      "history": [("human", "介绍下LLM"), ("ai", "LLM即大型语言模型,基于深度学习技术,能对语意进行理解。")],
      "question": "介绍LLM的一个核心技术点"
})

print(response)

下面即是LLM的回复,可以看到回答的信息是简短,而非通常回复几段话。

一个核心核心技术点是Transformer架构,它在处理序列数据时展现出强大的能力和效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值