提示词模板(Prompt Templates)
为什么推荐提示词模板?
在LangChain开发中,构造提示词既可以直接使用Python字符串拼接(如f-string、format()或+),也可以使用LangChain提供的PromptTemplate或ChatPromptTemplate。
举例1:字符串拼接方式
# 字符串拼接topic="python"difficulty="初学者"# 难以维护,容易出错prompt_str=f"你是一个{difficulty}级别的编程导师。请用简单的语言解释{topic}"response=model.invoke(prompt_str)print(response)举例2:提示词模板
from dotenvimportload_dotenv from langchain.chat_modelsimportinit_chat_model from langchain_core.promptsimportPromptTemplate topic="Python"difficulty="初学者"template=PromptTemplate.from_template(f"你是一个{difficulty}级别的编程导师,请用简单的语言解释{topic}")# 使用模板生成提示词prompt=template.format(difficulty=difficulty ,topic=topic)load_dotenv(override=True)model=init_chat_model(model="deepseek:deepseek-v4-flash")response=model.invoke(prompt)print(f"AI 回复:{response.content}")from langchain_core.promptsimportChatPromptTemplate prompt_template=ChatPromptTemplate([("system","你是一个AI开发工程师,你的名字是{name}"),("human","{user_input}")])# 调用format()方法,返回字符串prompt=prompt_template.invoke({"name":"小智AI","user_input":"你能帮我做什么"})print(type(prompt))print(f"AI 回复:{prompt}")response=model.invoke(prompt)print(response.content)ChatPromptTemplate的使用
在LangChain1.0中,ChatPromptTemplate是用于生成消息列表的核心组件
ChatPromptTemplate是创建聊天消息列表的提示模板。它比普通PromptTemplate更适合处理多角色、多轮次的对话场景。支持System/Human/AI等不同角色的消息模板。
消息类型:
| 角色字符串 | 含义 | 用途 |
|---|---|---|
| “system” | 系统消息 | 设定AI的行为、角色、规则 |
| “user”/“human” | 用户消息 | 用户的输入/问题 |
| “assistant”/“ai” | AI消息 | AI的回复(用于对话历史) |
两种实例化方式
ChatPromptTemplate可以通过初始化方法或from_messages方法来实例化提示词模板。实例化时需要传入messages参数。常见类型是:tuple构成的列表,参数类型(role:str,content:str)
方式1(推荐):调用from_messages()
该方法允许传入一个由元组(Tuple)构成的列表,列表中的每一个元组都代表一条具有特定角色的消息
chat_prompt_template=ChatPromptTemplate.from_messages([("system","你是一个友好的AI助手,你的名字叫{name}"),("human","你好,最近如何"),("ai","我很好,谢谢"),("human","{user_input}")])print(type(chat_prompt_template))result=chat_prompt_template.invoke({"name":"小智","user_input":"1 + 1 = ?"})response=model.invoke(result)print(response.content)方式2:使用实例初始化方法
chat_prompt_template=ChatPromptTemplate([("system","你是一个友好的AI助手,你的名字叫{name}"),("human","你好,最近如何"),("ai","我很好,谢谢"),("human","{user_input}")])print(type(chat_prompt_template))result=chat_prompt_template.invoke({"name":"小智","user_input":"1 + 1 = ?"})response=model.invoke(result)print(response.content)模板调用的三种方式
使用invoke()
返回ChatPromptValue
使用format()
返回值是字符串
使用format_messages()
返回值是list