from langchain.prompts import PromptTemplate
prompt_template = PromptTemplate.from_template(
"Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")
# > 'Tell me a funny joke about chickens.'
# 无变量
prompt_template = PromptTemplate.from_template("Tell me a joke")
prompt_template.format()
# > 'Tell me a joke'
PromptTemplate 一般使用在单轮对话中。不需要历史记忆的场景。
ChatPromptTemplate
ChatPromptTemplate 聊天消息列表,每条聊天消息都与内容以及附加参数相关联 role。例如聊天消息可以与 AI 助手、人类或系统角色相关联。
创建一个这样的聊天提示模板:
from langchain_core.prompts import ChatPromptTemplate
chat_template = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful AI bot. Your name is {name}."),
("human", "Hello, how are you doing?"),
("ai", "I'm doing well, thanks!"),
("human", "{user_input}"),
]
)
messages = chat_template.format_messages(name="Bob", user_input="What is your name?")
chat_template = ChatPromptTemplate.from_messages(
[
# 这里跟上面的 system 的作用是一致的
SystemMessage(
content=(
"You are a helpful assistant that re-writes the user's text to ""sound more upbeat."
)
),
HumanMessagePromptTemplate.from_template("{text}"),
]
)
messages = chat_template.format_messages(text="I don't like eating tasty things")
print(messages)
prompt_val = prompt_template.invoke({"adjective": "funny", "content": "chickens"})
# StringPromptValue(text='Tell me a funny joke about chickens.')
prompt_val.to_string()
# > Tell me a funny joke about chickens.
prompt_val.to_messages()
#> [HumanMessage(content='Tell me a joke')]
另一个例子
chat_val = chat_template.invoke({"text": "i dont like eating tasty things."})
chat_val.to_messages()
#> [SystemMessage(content="You are a helpful assistant that re-writes the user's text to sound more upbeat."),HumanMessage(content='i dont like eating tasty things.')]# 转换为字符串
chat_val.to_string()
#> "System: You are a helpful assistant that re-writes the user's text to sound more upbeat.\nHuman: i dont like eating tasty things."
Give the antonym of every input
Input: happy
Output: sad
Input: tall
Output:shortInput: energetic
Output: lethargic
Input: sunny
Output: gloomy
Input: windy
Output: calm
Input: big
Output:
一个包含长输入的示例,所以它只选择了一个示例。
long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else"print(dynamic_prompt.format(adjective=long_string))
Give the antonym of every input
Input: happy
Output: sad
Input: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything elseOutput: