(LangChain实战5):LangChain消息模版ChatPromptTemplate

一、ChatPromptTemplate简介

ChatPromptTemplate是LangChain中用于构建对话式提示词的专用模板。相比普通的PromptTemplate,它能更好地处理多角色对话场景,支持System、Human、AI等多种消息类型。

二、创建ChatPromptTemplate的两种方式

2.1 构造方法实例化

python 复制代码
from langchain.prompts import ChatPromptTemplate

# 方式一:使用构造方法
chat_prompt = ChatPromptTemplate(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ],
    input_variables=["name", "question"],  # 明确指定输入变量
)

# 简洁写法
chat_prompt = ChatPromptTemplate([
    ("system", "你是一个AI助手,你的名字叫{name}"),
    ("human", "我的问题是{question}")
])

2.2 from_messages()方法

python 复制代码
# 方式二:使用from_messages()方法(推荐)
chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个AI助手,你的名字叫{name}"),
    ("human", "我的问题是{question}")
])

两种方式对比:

  • 构造方法更灵活,可指定input_variables
  • from_messages()更简洁,自动推断变量

三、调用模板的四种方法

3.1 invoke()方法

python 复制代码
# invoke(): 传入字典,返回ChatPromptValue对象
response = chat_prompt.invoke(
    input={"name": "小智", "question": "1 + 2 + 3 = ?"}
)
print(f"返回类型: {type(response)}")
print(f"内容: {response}")

输出:

复制代码
返回类型: <class 'langchain_core.prompt_values.ChatPromptValue'>
内容: messages=[
    SystemMessage(content='你是一个AI助手,你的名字叫小智'),
    HumanMessage(content='我的问题是1 + 2 + 3 = ?')
]

3.2 format()方法

python 复制代码
# format(): 传入变量值,返回格式化字符串
formatted_text = chat_prompt.format(
    name="小智", 
    question="1 + 2 + 3 = ?"
)
print(f"返回类型: {type(formatted_text)}")
print(f"内容:\n{formatted_text}")

输出:

复制代码
返回类型: <class 'str'>
内容:
System: 你是一个AI助手,你的名字叫小智
Human: 我的问题是1 + 2 + 3 = ?

3.3 format_messages()方法

python 复制代码
# format_messages(): 传入变量值,返回消息列表
messages_list = chat_prompt.format_messages(
    name="小智",
    question="1 + 2 + 3 = ?"
)
print(f"返回类型: {type(messages_list)}")
print(f"内容: {messages_list}")

输出:

复制代码
返回类型: <class 'list'>
内容: [
    SystemMessage(content='你是一个AI助手,你的名字叫小智'),
    HumanMessage(content='我的问题是1 + 2 + 3 = ?')
]

3.4 format_prompt()方法

python 复制代码
# format_prompt(): 传入变量值,返回ChatPromptValue
prompt_value = chat_prompt.format_prompt(
    name="小智",
    question="1 + 2 + 3 = ?"
)
print(f"返回类型: {type(prompt_value)}")
print(f"内容: {prompt_value}")

输出:

复制代码
返回类型: <class 'langchain_core.prompt_values.ChatPromptValue'>
内容: messages=[
    SystemMessage(content='你是一个AI助手,你的名字叫小智'),
    HumanMessage(content='我的问题是1 + 2 + 3 = ?')
]

四、四种方法对比总结

方法 输入类型 输出类型 适用场景
invoke() 字典 ChatPromptValue 链式调用,需要结构化响应
format() 关键字参数 字符串 需要人类可读的文本
format_messages() 关键字参数 消息列表 需要直接传递给聊天模型
format_prompt() 关键字参数 ChatPromptValue 需要中间格式进行后续处理

五、完整版调用模型

python 复制代码
import os
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv

# 加载env环境变量
load_dotenv()

# 获取对话模型
chat_model = ChatOpenAI(
    # 1.设置模型名称
    model="deepseek-chat",
    # 2.模型接口地址
    base_url= os.getenv('OPENAI_BASE_URL'),
    # 3.模型调用key
    api_key=os.getenv('OPENAI_API_KEY'),
)


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

# 填充模版参数
prompt = chat_prompt_template.invoke(input={"name": "小智", "question": "1 + 2 + 3 = ? "})

# 通过大模型调用提示词,得到响应数据
response = chat_model.invoke(prompt)
print(response)
相关推荐
China_Yanhy5 小时前
动手学大模型第一篇学习总结
人工智能
空间机器人5 小时前
自动驾驶 ADAS 器件选型:算力只是门票,系统才是生死线
人工智能·机器学习·自动驾驶
C+++Python5 小时前
提示词、Agent、MCP、Skill 到底是什么?
人工智能
小松要进步5 小时前
机器学习1
人工智能·机器学习
Mr_Xuhhh5 小时前
Java泛型进阶:从基础到高级特性完全指南
开发语言·windows·python
泰恒5 小时前
openclaw近期怎么样了?
人工智能·深度学习·机器学习
KaneLogger6 小时前
从传统笔记到 LLM 驱动的结构化 Wiki
人工智能·程序员·架构
tinygone6 小时前
OpenClaw之Memory配置成本地模式,Ubuntu+CUDA+cuDNN+llama.cpp
人工智能·ubuntu·llama
斯外戈的小白6 小时前
【Agent】LangChain 1.0架构
架构·langchain
正在走向自律6 小时前
第二章-AIGC入门-AIGC工具全解析:技术控的效率神器,DeepSeek国产大模型的骄傲(8/36)
人工智能·chatgpt·aigc·可灵·deepseek·即梦·阿里通义千问