LangChain使用之Model IO(提示词模版之ChatPromptTemplate)

1、实例化方法

ChatPromptTemplate是创建聊天消息列表 的提示模版,他比普通的PromptTemplate更适合处理多角色、多轮次的对话场景。

他的实例化有两种方式:使用构造方法和from_messages(),列表参数格式是tuple(元组)类型。

方式一:使用构造方法

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate(
    messages = [
        ("system","你是一个AI助手,你的名字叫{name}"),
        ("human","我的问题是{question}")
    ],
    input_variables = ["name","question"]
)

response = chat_prompt_template.invoke(input = {"name":"小智","question":"你是哪个公司旗下的产品?"})
print(response)

方式二:使用from_messages()方法✅️

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages(
    messages = [
        ("system","你是一个AI助手,你的名字叫{name}"),
        ("human","我的问题是{question}")
    ]
)

response = chat_prompt_template.invoke(input = {"name":"小智","question":"你是哪个公司旗下的产品?"})
print(response)
print(type(response)) #ChatPromptValue

2、提示词调用模版的方法

调用模版共有四种方式:

  • invoke():参数传入的是字典,返回的是ChatPromptValue
  • format():参数传入的是变量的值,返回字符串str
  • format_messages():参数传入的是变量的值,返回消息构成的列表list
  • format_prompt():参数传入的是变量的值,返回ChatPromptValue.

对于第一种方式,在前文的实例化章节中已经应用。

示例2:format()

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages(
    messages = [
        ("system","你是一个AI助手,你的名字叫{name}"),
        ("human","我的问题是{question}")
    ]
)

response = chat_prompt_template.format(name = "小智",question = "你是哪个公司旗下的产品?")
print(response)
print(type(response)) #str

示例3:format_messages()

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages(
    messages = [
        ("system","你是一个AI助手,你的名字叫{name}"),
        ("human","我的问题是{question}")
    ]
)

response = chat_prompt_template.format_messages(name = "小智",question = "你是哪个公司旗下的产品?")
print(response)
print(type(response)) #list

示例4:format_prompt()

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages(
    messages = [
        ("system","你是一个AI助手,你的名字叫{name}"),
        ("human","我的问题是{question}")
    ]
)

response = chat_prompt_template.format_prompt(name = "小智",question = "你是哪个公司旗下的产品?")
print(response)
print(type(response)) #ChatPromptValue

3、实现输出类型的转换

以下示例中的response为调用模版时候的示例4,返回值类型是ChatPromptValue。

(1)ChatPromptValue->list

python 复制代码
response_message = response.to_messages() # ChatPromptValue转换为list
print(type(response))
print(response_message)
print(type(response_message))

(2)ChatPromptValue->str

python 复制代码
response_string = response.to_string() # ChatPromptValue转换为string
print(type(response))
print(response_string)
print(type(response_string))

4、其他实例化参数类型

无论是采用构造方法还是from_messages()来构建ChatPromptTemplate的实例,本质上都是传入消息构成的列表 。 从调用上来说,不管使用构造方法还是from_messages(),messages的参数类型都是列表,但是列表的元素类型多样,可以是:++字符串类型、字典类型、消息类型、元组构成的列表✅️、Chat提示词模版类型、消息提示词模版类型++。

示例4(消息类型)和示例6(消息提示词模版类型)都是消息,前者不用参数时使用,后者可以搭配参数使用。

示例1:元组构成的列表

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate([
        ("system","你是一个AI助手,你的名字叫{name}"),
        ("human","我的问题是{question}")
    ])

response = chat_prompt_template.invoke(input = {"name":"小智","question":"你是哪个公司旗下的产品?"})
print(response)

示例2:字符串类型

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate([
    "我的问题是{question}"
    ]) # 默认角色是Human

response = chat_prompt_template.invoke(input = {"question":"你是哪个公司旗下的产品?"})
print(response)

示例3:字典类型

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate([
    {"role":"system","content":"我是人工智能,名字叫{name}"},
    {"role":"human","content":"我的问题是{question}"},
    ])

response = chat_prompt_template.invoke(input = {"name":"小志","question":"你是哪个公司旗下的产品?"})
print(response)

示例4:消息类型

python 复制代码
from langchain_core.messages import SystemMessage,HumanMessage
from langchain_core.prompts import ChatPromptTemplate

# 创建实例
chat_prompt_template = ChatPromptTemplate([
    SystemMessage(content = "我是人工智能,名字叫{name}"),
    HumanMessage(content = "我的问题是{question}")
    ])

#response = chat_prompt_template.invoke(input = {"name":"小志","question":"你是哪个公司旗下的产品?"})
response = chat_prompt_template.invoke(input = {})
print(response)

示例5:chat提示词模版

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)
nested_prompt_template1 = ChatPromptTemplate.from_messages([
    ("system", "我是一个人工智能助手,我的名字叫{name}")
])
nested_prompt_template2 = ChatPromptTemplate.from_messages([
    ("human", "很高兴认识你,我的问题是{question}")
])

prompt_template = ChatPromptTemplate.from_messages([
    nested_prompt_template1,nested_prompt_template2
])

prompt_template.format_messages(name="小智",question="你为什么这么帅?")

示例6:消息提示词模版类型

python 复制代码
# 导入聊天消息类模板
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate,SystemMessagePromptTemplate

# 创建消息模板
system_template = "你是一个专家{role}"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

human_template = "给我解释{concept},用浅显易懂的语言"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

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

# 格式化提示
formatted_messages = chat_prompt.format_messages(
    role="物理学家",
    concept="相对论"
)

print(formatted_messages)

5、结合LLM

python 复制代码
# 1、提供大模型
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
import os
import dotenv

dotenv.load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
os.environ["OPENAI_BASE_URL"] = os.getenv("OPENAI_BASE_URL")

chat_model = ChatOpenAI(
    model = "gpt-4o-mini"
)
# 2、通过提示词模版,创建提示词
chat_prompt_template = ChatPromptTemplate.from_messages([
    ("system","你是AI助手,你的名字是{name}"),
    ("human","我的问题是{question}")
])
# 3、通过LLM调用提示词,得到响应数据
prompt = chat_prompt_template.invoke(input={"name":"小志","question":"你是哪个公司旗下的?"})
response = chat_model.invoke(prompt)

print(response.content)

6、插入消息列表:MessagePlaceholder

适用场景:当ChatPromptTemplate模版中消息类型与个数不确定的时候,使用消息列表。

python 复制代码
from langchain_core.messages import AIMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts.chat import MessagesPlaceholder

chat_prompt_template = ChatPromptTemplate.from_messages([
    ("system","你是AI助手,你的名字是{name}"),
    MessagesPlaceholder(variable_name = "msgs")
])

chat_prompt_template.invoke(input = {
    "name":"小志",
    "msgs":[HumanMessage(content = "1+1=?"),AIMessage(content = "1+2=?")]  # HumanMessage AIMessage
})
相关推荐
ttwuai10 小时前
XYGo Admin 菜单与路由:Vue3 动态路由 + GoFrame 权限菜单的完整实现方案
前端·vue·后台框架
数智工坊10 小时前
【UniT论文阅读】:用统一物理语言打通人类与人形机器人的知识壁垒
论文阅读·人工智能·深度学习·算法·机器人
BIG_PEI10 小时前
检查并安装Redis
java
Lyon1985052810 小时前
ChatGPT的最终总结分析-《文字定律》随笔
人工智能·ai·chatgpt
知识分享小能手10 小时前
Flask入门学习教程,从入门到精通, 认识Flask路由 — 知识点详解 (2)
python·学习·flask
AI棒棒牛10 小时前
YOLO26改进创新 | 全网首发!VECA弹性核心注意力重塑全局建模,线性复杂度增强检测骨干,嘎嘎创新!
python·yolo·目标检测·yolo26·主干改进
大貔貅喝啤酒10 小时前
基于Windows下载安装Android Studio 3.3.2版本教程(2026详细图文版)
android·java·windows·android studio
L、21810 小时前
CANN神经网络算子库`ops-nn`:昇腾NPU上Matmul与激活函数的底层逻辑
人工智能·深度学习·神经网络
奋斗的小方10 小时前
Java基础篇09:项目实战
java·开发语言
程序员码歌10 小时前
OpenSpec 到 Superpowers:AI 编码从说清到做对
android·前端·人工智能