2026-08-05
AI
0

目录

1. 消息
1.1 消息的content属性
1.2 content_blocks
2. 提示词模版
2.1 ChatPromptTemplate的使用
2.1.1 两种实例化方式
2.2 ChatPromptTemplate的调用
2.3 结合LLM调用
2.4 更丰富的初始化参数类型
2.4.1 类型1:str列表类型
2.4.2 类型2:tuple列表类型
2.4.3 类型3:dict列表类型
2.4.4 类型4:Message列表类型
2.4.5 类型5:MessagePromptTemplate列表类型
2.4.6 类型6:BaseChatPromptTemplate列表类型
2.5 其它特性
2.5.1 部分变量预填充:partial()
2.5.2 消息占位符
2.5.3 可复用的模版库
2.5.4 模版组合

上一篇中我们介绍了环境搭建与LangChain model组件的基本使用,本章节说一下消息与提示词相关的内容,在langchain1.x版本有一些新的内容。

1. 消息

1.1 消息的content属性

消息的 content 可以理解为数据内容,它是弱类型的,支持字符串和列表(列表元素通常为字典)。

举例1:存储字符串

如果只是纯文本内容,直接传递字符串就好

python
from LangChain.messages import HumanMessage msg1 = HumanMessage(content = "你好啊") msg2 = HumanMessage("你好啊") print(msg1) print(msg2)

说明:当content内容只有字符串时,可以省略参数名称。

举例2:存储字典列表

如果需要发送的不只是文本,如多模态内容,则需要content的 字典列表 形式。 字典内容遵循模型供应商的API规范,这里使用qwen模型进行多模态输入测试

python
import base64 import os from dotenv import load_dotenv from langchain.chat_models import init_chat_model from langchain_core.messages import HumanMessage load_dotenv() model = init_chat_model( model="qwen3.7-plus", model_provider="openai", # 关键:指定使用openai兼容协议 api_key=os.getenv("DASHSCOPE_API_KEY"), base_url=os.getenv("DASHSCOPE_API_BASE_URL") ) def encode_image(img_path, img_type='jpeg'): """将一张本地图片转换成 Base64 编码的 Data URI 字符串,方便在文本中嵌入图片数据""" with open(img_path, "rb") as img_file: return f"data:image/{img_type};base64,{base64.b64encode(img_file.read()).decode("utf-8")}" # 图像路径 img_path = "image_test.png" # 获取图像base64编码字符串 base64_image = encode_image(img_path) response = model.invoke( [ HumanMessage( content=[ {'type': 'text', 'text': '这张图里有什么?'}, { 'type': 'image_url', "image_url": base64_image, } ] ) ] ) print(response.content)

image.png

1.2 content_blocks

在 LangChain 1.x 中, content_blocks 是消息对象(BaseMessage)的一项重大升级。它的核心目标是提供一种跨模型供应商、标准化的多模态数据结构。

过去,处理图片、音频、甚至是模型生成的“思维链(Reasoning)”内容时,不同供应商(OpenAI, Anthropic, Google 等)的 API 格式各异,导致开发者需要写大量的适配代码。 content_blocks 的出现终结了这种混乱。

在 LangChain 1.2 版本中,消息对象的 content 属性依然存在(为了向前兼容),但新增了 content_blocks 属性,可以将 content 解析为标准、类型安全的表示。

  • 数据结构:它是一个 list[TypedDict]
  • 统一格式:每个 block 都有一个 type 字段,用于区分内容类型。
  • 支持类型:包括 text (文本)、 image (图片)、 audio (音频)、 video (视频)、tool_call (工具调用)以及 reasoning (推理/思维链)。

支持的字段类型详见https://docs.langchain.com/oss/python/langchain/messages#openai

① 输入格式化

对于复杂的对话(带图片或工具结果),建议使用 content_blocks 列表形式构建 HumanMessage 或 AIMessage。借助 content_blocks ,我们可以用一套标准代码,无缝地在不同厂商的模型之间切换。

python
import base64 import os from dotenv import load_dotenv from langchain.chat_models import init_chat_model from langchain_core.messages import HumanMessage load_dotenv() # model = init_chat_model( # model="qwen3.7-plus", # model_provider="openai", # 关键:指定使用openai兼容协议 # api_key=os.getenv("DASHSCOPE_API_KEY"), # base_url=os.getenv("DASHSCOPE_API_BASE_URL") # ) model = init_chat_model( model="deepseek-v4-flash", api_key=os.getenv("DEEPSEEK_API_KEY"), api_base=os.getenv("DEEPSEEK_BASE_URL"), ) def encode_image(img_path, img_type='jpeg'): """将一张本地图片转换成 Base64 编码的 Data URI 字符串,方便在文本中嵌入图片数据""" with open(img_path, "rb") as img_file: return f"data:image/{img_type};base64,{base64.b64encode(img_file.read()).decode("utf-8")}" # 图像路径 img_path = "image_test.png" # 获取图像base64编码字符串 base64_image = encode_image(img_path) response = model.invoke( [ HumanMessage( content_blocks=[ {'type': 'text', 'text': '这张图里有什么?'}, { 'type': 'image', 'base64': base64_image, 'mime_type': 'image/png', } ] ) ] ) print(response.content)

注意: 上面的代码知识演示,content_blocks由于是1.2新出的,有些模型不一定支持。

② 输出格式化

content_blocks 还可用于输出格式化,以deepseek官网的 deepseek-v4-flash 为例,其输出包含思考内容,后者位于 additional_kwargs 的 reasoning_content 字段下。

不同的模型其输出格式可能不同,仅为提取思考内容,切换模型都可能需要更改代码,非常不方便。 content_blocks提供了 统一的输出格式 ,可以将不同格式的响应统一为标准格式。 注意:content_blocks是 懒加载 的,即调用时才会解析。

python
import os from dotenv import load_dotenv from langchain.chat_models import init_chat_model load_dotenv() model = init_chat_model( model="deepseek-v4-flash", api_key=os.getenv("DEEPSEEK_API_KEY"), api_base=os.getenv("DEEPSEEK_BASE_URL"), extra_body={"thinking": {"type": "enabled"}}, ) response = model.invoke("你好,一句话回答") print('=' * 20, '-> response <-', '=' * 20) print(response) print('=' * 20, '-> response.content <-', '=' * 20) print(response.content) print('=' * 20, '-> response.content_blocks <-', '=' * 20) print(response.content_blocks)

image.png 说明:优先检查 response.content_blocks 而不是 response.content ,特别是当你需要获取“思维链”或者“引用(Citations)”信息时。

2. 提示词模版

在 LangChain 开发中,构造提示词既可以直接使用 Python 字符串拼接(如 f-string、format() 或+),也可以使用 LangChain 提供的 PromptTemplate 或 ChatPromptTemplate 。

举例1:字符串拼接方式

python
# 字符串拼接 topic = "Python" difficulty = "初学者" # 难以维护,容易出错 prompt_str = f"你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。" response = model.invoke(prompt_str) print(f"AI 回复:{response.content}...\n")

举例2:提示词模板

python
from langchain.prompts import PromptTemplate topic = "Python" difficulty = "初学者" template = PromptTemplate.from_template( "你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。" ) # 使用模板生成提示词 prompt = template.format(difficulty=difficulty, topic=topic) response = model.invoke(prompt) print(f"AI 回复:{response.content}...\n")
python
from langchain_core.prompts import ChatPromptTemplate prompt_template = ChatPromptTemplate([ ("system", "你是一个AI开发工程师. 你的名字是 {name}."), ("human", "{user_input}") ]) #调用format()方法,返回字符串 prompt = prompt_template.invoke({"name":"小谷AI", "user_input":"你能帮我做什 么?"}) print(prompt)

PromptTemplate与ChatPromptTemplate对比

特性PromptTemplateChatPromptTemplate
输出格式纯文本字符串消息列表
角色支持❌ 无✅ system/user/assistant
对话历史❌ 不支持3
适用场景✅ 支持聊天、对话、多轮交互

2.1 ChatPromptTemplate的使用

在LangChain 1.0中,ChatPromptTemplate 是用于生成消息列表的核心组件。 ChatPromptTemplate是创建 聊天消息列表 的提示模板。它比普通 PromptTemplate 更适合处理多角色、多轮次的对话场景。支持 System / Human / AI 等不同角色的消息模板。 消息类型只支持如下五种:systemaiassistantuserhuman

2.1.1 两种实例化方式

ChatPromptTemplate 可以通过 初始化方法 或 from_messages 方法来实例化提示词模板。实例化时需要传入 messages参数 。常见类型是:tuple构成的列表,参数类型(role : str,content : str )

方式1(推荐):调用from_messages()

该方法允许传入一个由元组(Tuple)构成的列表,列表中的每一个元组都代表一条具有特定角色的消 息。

python
# 导入相关依赖 from langchain_core.prompts import ChatPromptTemplate # 定义聊天提示词模版 chat_template = ChatPromptTemplate.from_messages( [ ("system", "你是一个有帮助的AI机器人,你的名字是{name}。"), ("human", "你好,最近怎么样?"), ("ai", "我很好,谢谢!"), ("human", "{user_input}"), ] ) # 格式化聊天提示词模版中的变量 prompt = chat_template.invoke({"name": "小明", "user_input": "你叫什么名字?"}) # 打印格式化后的聊天提示词模版内容 print(prompt) # 输出如下: # messages=[SystemMessage(content='你是一个有帮助的AI机器人,你的名字是小明。', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好,最近怎么样?', additional_kwargs={}, response_metadata={}), AIMessage(content='我很好,谢谢!', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[]), HumanMessage(content='你叫什么名字?', additional_kwargs={}, response_metadata={})]

方式2:使用实例初始化方法

python
from langchain_core.prompts import ChatPromptTemplate #参数类型这里使用的是tuple构成的list prompt_template = ChatPromptTemplate([ # 字符串 role + 字符串 content ("system", "你是一个AI开发工程师. 你的名字是 {name}."), ("human", "你能开发哪些AI应用?"), ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."), ("human", "{user_input}") ]) #调用invoke()方法,返回ChatPromptValue prompt = prompt_template.invoke({"name": "小谷AI", "user_input": "你能帮我做什么?"}) print(prompt)

这两种方式在底层都是通过调用__init__方法实现的

2.2 ChatPromptTemplate的调用

ChatPromptTemplate有三种调用方式: invoke()format()format_messages()

方式1:使用 invoke()

传入参数:字典列表

返回:ChatPromptValue

python
chat_template = ChatPromptTemplate.from_messages( [ ("system", "你是一个有帮助的AI机器人,你的名字是{name}。"), ("human", "你好,最近怎么样?"), ("ai", "我很好,谢谢!"), ("human", "{user_input}"), ] ) # 格式化聊天提示词模版中的变量 prompt = chat_template.invoke({"name": "小明", "user_input": "你叫什么名字?"}) # messages=[SystemMessage(content='你是一个有帮助的AI机器人,你的名字是小明。', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好,最近怎么样?', additional_kwargs={}, response_metadata={}), AIMessage(content='我很好,谢谢!', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[]), HumanMessage(content='你叫什么名字?', additional_kwargs={}, response_metadata={})]

方式2:使用format()

返回字符串

python
from langchain_core.prompts import ChatPromptTemplate #参数类型这里使用的是tuple构成的list prompt_template = ChatPromptTemplate([ # 字符串 role + 字符串 content ("system", "你是一个AI开发工程师. 你的名字是 {name}."), ("human", "你能开发哪些AI应用?"), ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."), ("human", "{user_input}") ]) #方式1:调用format()方法,返回字符串 prompt = prompt_template.format(name="小谷AI", user_input="你能帮我做什么?") print(type(prompt)) print(prompt) # <class 'str'> # System: 你是一个AI开发工程师. 你的名字是 小谷AI. # Human: 你能开发哪些AI应用? # AI: 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等. # Human: 你能帮我做什么?

方式3:使用format_messages()

返回消息列表

python
from langchain_core.prompts import ChatPromptTemplate prompt_template = ChatPromptTemplate.from_messages([ ("system", "你是一个AI开发工程师. 你的名字是 {name}."), ("human", "你能开发哪些AI应用?"), ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."), ("human", "{user_input}") ]) #调用format_messages()方法,返回消息列表 prompt = prompt_template.format_messages(name="小谷AI", user_input="你能帮我做什么?") print(type(prompt)) print(prompt) # <class 'list'> #[SystemMessage(content='你是一个AI开发工程师. 你的名字是 小谷AI.', additional_kwargs={}, response_metadata={}), HumanMessage(content='你能开发哪些AI应用?', additional_kwargs={}, response_metadata={}), AIMessage(content='我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[]), HumanMessage(content='你能帮我做什么?', additional_kwargs={}, response_metadata={})]

2.3 结合LLM调用

python
import os from dotenv import load_dotenv from langchain.chat_models import init_chat_model load_dotenv() model = init_chat_model( model="qwen3.7-plus", model_provider="openai", # 关键:指定使用openai兼容协议 api_key=os.getenv("DASHSCOPE_API_KEY"), base_url=os.getenv("DASHSCOPE_API_BASE_URL") ) ######2、提供提示词######### chat_prompt = ChatPromptTemplate.from_messages([ ("system", "你是一个数学家,你可以计算任何算式"), ("human", "{text}"), ]) # 输入提示 prompt_value = chat_prompt.invoke({ "text": "我今年18岁,我的舅舅今年38岁,我的爷爷今年72岁,我和舅舅一共多少岁了?" }) ######3、结合提示词,调用大模型######### # 得到模型的输出 output = model.invoke(prompt_value) # 打印输出内容 print(output.content)

2.4 更丰富的初始化参数类型

2.4.1 类型1:str列表类型

python
#1.导入相关依赖 from langchain_core.prompts import ChatPromptTemplate chat_template = ChatPromptTemplate.from_messages( [ "Hello, {name}!" # 等价于 ("human", "Hello, {name}!") ] ) # 3. 使用invoke执行 messages = chat_template.invoke({"name": "小谷AI"})

2.4.2 类型2:tuple列表类型

列表参数格式是元组类型

python
prompt = ChatPromptTemplate.from_messages([ ("system", "你的名字是{role}."), ("human", "很高兴认识你"), ]) print(prompt.invoke({"role": "小智"}))

2.4.3 类型3:dict列表类型

列表参数格式是dict类型

python
prompt = ChatPromptTemplate.from_messages([ {"role": "system", "content": "你的名字是{role}."}, {"role": "human", "content": "很高兴认识你"}, ]) print(prompt.invoke({"role": "小智"}))

2.4.4 类型4:Message列表类型

python
from langchain_core.messages import SystemMessage, HumanMessage chat_prompt_template = ChatPromptTemplate.from_messages([ SystemMessage(content="我是一个贴心的智能助手"), HumanMessage(content="我的问题是:人工智能英文怎么说?") ]) messages = chat_prompt_template.invoke({})

注意: 这种格式不呢个有占位符

🙅错误示范

python
from langchain_core.messages import SystemMessage,HumanMessage chat_prompt_template = ChatPromptTemplate.from_messages([ SystemMessage(content="我是一个贴心的智能助手"), HumanMessage(content="我的问题是:{word}英文怎么说?") ]) messages = chat_prompt_template.invoke({"word":"人工智能"})

2.4.5 类型5:MessagePromptTemplate列表类型

可以解决类型4不能传占位符的问题

LangChain提供不同类型的MessagePromptTemplate。最常用的是 SystemMessagePromptTemplate 、 HumanMessagePromptTemplate 和 AIMessagePromptTemplate ,分别创建系统消息、人工消息和AI消息。

基本概念: HumanMessagePromptTemplate,专用于生成 用户消息(HumanMessage) 的模板类

  • 模板化 :支持使用变量占位符,可以在运行时填充具体值
  • 格式化 :能够将模板与输入变量结合生成最终的聊天消息
  • 输出类型 :生成 HumanMessage 对象( content + role="human" )
  • 设计目的 :简化用户输入消息的模板化构造,避免重复定义角色 SystemMessagePromptTemplate、AIMessagePromptTemplate:类似于上面,不再赘述
python
# 导入聊天消息类模板 from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate # 创建消息模板 system_message_prompt = SystemMessagePromptTemplate.from_template("你是一个{role}") human_message_prompt = HumanMessagePromptTemplate.from_template("给我解释{concept},用浅显易懂的语言") # 组合成聊天提示模板 chat_prompt = ChatPromptTemplate.from_messages([ system_message_prompt, human_message_prompt ]) # 格式化提示 formatted_messages = chat_prompt.invoke({"role": "物理学家", "concept": "相对"}) print(formatted_messages) # messages=[SystemMessage(content='你是一个物理学家', additional_kwargs={}, response_metadata={}), HumanMessage(content='给我解释相对,用浅显易懂的语言', additional_kwargs={}, response_metadata={})]

2.4.6 类型6:BaseChatPromptTemplate列表类型

使用 BaseChatPromptTemplate,可以理解为ChatPromptTemplate里嵌套了 ChatPromptTemplate。

案例1: 带参数

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.invoke({"name": "小智", "question": "你为什么这么帅?"}) # ChatPromptValue(messages=[SystemMessage(content='我是一个人工智能助手,我的名字叫小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='很高兴认识你,我的问题是你为什么这么帅?', additional_kwargs={}, response_metadata={})])

案例2: 不带参数

python
from langchain_core.prompts import ChatPromptTemplate # 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate) nested_prompt_template1 = ChatPromptTemplate.from_messages([("system", "我是一个人工智能助手")]) nested_prompt_template2 = ChatPromptTemplate.from_messages([("human", "很高兴认识你")]) prompt_template = ChatPromptTemplate.from_messages([ nested_prompt_template1, nested_prompt_template2 ]) prompt_template.invoke({}) # ChatPromptValue(messages=[SystemMessage(content='我是一个人工智能助手', additional_kwargs={}, response_metadata={}), HumanMessage(content='很高兴认识你', additional_kwargs={}, response_metadata={})])

案例3: 综合使用

python
from langchain_core.prompts import ( SystemMessagePromptTemplate, HumanMessagePromptTemplate, ) from langchain_core.messages import SystemMessage, HumanMessage # 示例 1: 使用 BaseMessage(已实例化的消息) system_msg = SystemMessage(content="你是一个AI工程师。") human_msg = HumanMessage(content="你好!") # 示例 2: 使用 BaseMessagePromptTemplate system_prompt = SystemMessagePromptTemplate.from_template("你是一个{role}.") human_prompt = HumanMessagePromptTemplate.from_template("{user_input}") # 示例 3: 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate) nested_prompt = ChatPromptTemplate.from_messages([("system", "嵌套提示词")]) prompt = ChatPromptTemplate.from_messages([ system_msg, # MessageLike (BaseMessage) human_msg, # MessageLike (BaseMessage) system_prompt, # MessageLike (BaseMessagePromptTemplate) human_prompt, # MessageLike (BaseMessagePromptTemplate) nested_prompt, # MessageLike (BaseChatPromptTemplate) ]) prompt.invoke({"role": "人工智能专家", "user_input": "介绍一下大模型的应用场景"})

2.5 其它特性

2.5.1 部分变量预填充:partial()

预填充某些固定不变的变量,创建模板的变体。 使用场景:

  • 某些变量在所有调用中都相同
  • 需要为不同用户/场景创建定制模板
python
from langchain_core.prompts import ChatPromptTemplate # 原始模板 template = ChatPromptTemplate.from_messages([ ("system", "你是{role},目标用户是{audience}"), ("user", "{task}") ]) # 部分填充 customer_support_template = template.partial( role="客服专员", audience="普通用户" ) # 现在只需要提供 task messages = customer_support_template.invoke({"task": "解释退款政策"}) print(messages) # messages=[SystemMessage(content='你是客服专员,目标用户是普通用户', additional_kwargs={}, response_metadata={}), HumanMessage(content='解释退款政策', additional_kwargs={}, response_metadata={})]

案例2:

python
# 场景:为不同部门创建专用模板 base_template = ChatPromptTemplate.from_messages([ ("system", "你是{department}的{role}"), ("user", "{task}") ]) # IT 部门 it_template = base_template.partial( department="IT 部门", role="技术支持" ) # 销售部门 sales_template = base_template.partial( department="销售部门", role="销售顾问" ) sales_template.invoke({"task": "为什么每年年底汽车会促销"}) # ChatPromptValue(messages=[SystemMessage(content='你是销售部门的销售顾问', additional_kwargs={}, response_metadata={}), HumanMessage(content='为什么每年年底汽车会促销', additional_kwargs={}, response_metadata={})])

2.5.2 消息占位符

当你不确定消息提示模板使用什么角色,或者希望在格式化过程中 插入消息列表 时,该怎么办? 这就 需要使用消息占位符,负责在特定位置添加消息列表。

使用场景:多轮对话系统存储历史消息以及Agent的中间步骤处理此功能非常有用。

方式1:JSON形式

python
from langchain_core.prompts import ChatPromptTemplate template = ChatPromptTemplate.from_messages( [ ("system", "你是一个有用的AI助手"), ("placeholder", "{conversation}"), ] ) prompt_value = template.invoke( { "conversation": [ ("human", "你好!"), ("ai", "今天我能帮你做什么?"), ("human", "你能给我做一个冰激凌吗?"), ("ai", "抱歉,我没有这样的能力"), ] } ) print(prompt_value) # messages=[SystemMessage(content='你是一个有用的AI助手', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好!', additional_kwargs={}, response_metadata={}), AIMessage(content='今天我能帮你做什么?', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[]), HumanMessage(content='你能给我做一个冰激凌吗?', additional_kwargs={}, response_metadata={}), AIMessage(content='抱歉,我没有这样的能力', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[])]

方式2:MessagesPlaceholder实例

python
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.messages import HumanMessage prompt_template = ChatPromptTemplate.from_messages([ ("system", "You are a helpful assistant"), MessagesPlaceholder("msgs") ]) prompt_template.invoke({"msgs": [HumanMessage(content="hi!")]}) # ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant', additional_kwargs={}, response_metadata={}), HumanMessage(content='hi!', additional_kwargs={}, response_metadata={})])

举例2:存储对话历史内容

python
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder prompt_template = ChatPromptTemplate.from_messages( [ ("system", "你是一个非常友好的AI助手"), MessagesPlaceholder(variable_name="history"), ("human", "{question}") ] ) prompt_template.invoke( { "history": [ ("human", "5 + 2 = ?"), ("ai", "5 + 2 = 7") ], "question": "结果再乘以4呢?" } ) # ChatPromptValue(messages=[SystemMessage(content='你是一个非常友好的AI助手', additional_kwargs={}, response_metadata={}), HumanMessage(content='5 + 2 = ?', additional_kwargs={}, response_metadata={}), AIMessage(content='5 + 2 = 7', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[]), HumanMessage(content='结果再乘以4呢?', additional_kwargs={}, response_metadata={})])

2.5.3 可复用的模版库

定义具体存放模版的py文件 templates.py

python
from langchain_core.prompts import ChatPromptTemplate class PromptLibrary: """可复用的提示词模板库""" TRANSLATOR = ChatPromptTemplate.from_messages([ ("system", "你是专业翻译,精通{source_lang}和{target_lang}"), ("user", "翻译以下文本:\n{text}") ]) CODE_REVIEWER = ChatPromptTemplate.from_messages([ ("system", "你是{language}代码审查专家,重点关注{focus}"), ("user", "审查代码:\n```{language}\n{code}\n```") ]) SUMMARIZER = ChatPromptTemplate.from_messages([ ("system", "你是内容摘要专家"), ("user", "将以下内容总结为{num}个要点:\n{content}") ]) TUTOR = ChatPromptTemplate.from_messages([ ("system", "你是{subject}导师,学生水平:{level}"), ("user", "{question}") ])

在其它文件使用

python
from templates import PromptLibrary messages = PromptLibrary.TRANSLATOR.format_messages( source_lang="英语", target_lang="中文", text="Hello World" )

2.5.4 模版组合

将多个模板片段组合成复杂的提示词。

方法 1:字符串组合

python
# 定义可复用的部分 role_part = "你是一个{domain}专家。" style_part = "回答风格:{style}。" constraint_part = "限制:{constraint}。" # 组合 full_system = role_part + style_part + constraint_part template = ChatPromptTemplate.from_messages([ ("system", full_system), ("user", "{question}") ])

方法 2:使用 + 运算符

python
template1 = ChatPromptTemplate.from_messages([ ("system", "你是助手") ]) template2 = ChatPromptTemplate.from_messages([ ("user", "{input}") ]) # 组合(LangChain 1.0 支持) combined = template1 + template2
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:繁星

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!