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

1. 基本用途
**ChatPromptTemplate**为聊天式交互场景设计,用于构建多轮对话形式的提示信息。它可以处理不同角色(如人类、AI)的消息,并按照一定的格式组合这些消息。这更符合聊天机器人、对话式 AI 等应用的需求。ChatPromptTemplate能够处理不同角色,是与PromptTemplate最大的不同。
2.模板结构
**ChatPromptTemplate**由多个消息模板组成,每个消息模板对应一个特定的角色(如 HumanMessagePromptTemplate、AIMessagePromptTemplate 等)。这些消息模板可以包含各自的占位符,用于填充动态内容。例如:
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
LangChain ChatPromptTemplate基础使用指南

最低0.47元/天 解锁文章
537

被折叠的 条评论
为什么被折叠?



