from langchain_core.prompts import PromptTemplate, ChatPromptTemplate
# 1. 字符串提示词
prompt_template = PromptTemplate.from_template("hello, my name is {name}, nice to meet you")
print(prompt_template)
# 实例化
prompt_1=prompt_template.invoke({"name":"Alice"})
print(prompt_1) # text='hello, my name is Alice, nice to meet you'
# 提示词处理
# 转字符串
print(prompt_1.to_string()) # hello, my name is Alice, nice to meet you
# 转messages
print(prompt_1.to_messages()) # [HumanMessage(content='hello, my name is Alice, nice to meet you', additional_kwargs={}, response_metadata={})]
# 2 聊天提示词模版
chat_prompt_template = ChatPromptTemplate.from_messages(
[
("system","回复内容不超过{max_len}个字"),
("user","hello, my name is {name}, nice to meet you"),
("user","hello")
]
)
prompt_2 = chat_prompt_template.invoke({"max_len":100,"name":"Alice"})
print(prompt_2.to_messages()) #[SystemMessage(content='回复内容不超过100个字', additional_kwargs={}, response_metadata={}), HumanMessage(content='hello, my name is Alice, nice to meet you', additional_kwargs={}, response_metadata={}), HumanMessage(content='hello', additional_kwargs={}, response_metadata={})]
LangChain使用提示词模版
于 2025-05-29 14:32:36 首次发布