【动手学Langchain】初级篇2-提示词模板

Posted by Orchid on February 19, 2025

什么是提示词模板

提示词模板(Prompt Template)是自然语言处理(NLP)和人工智能领域中的一种工具,用于生成高质量的输入提示(prompt),以引导语言模型生成符合预期的输出。简单来说,提示词模板是一种结构化的文本格式,通过插入动态参数预定义的文本内容,帮助语言模型更好地理解任务需求,从而提高生成结果的质量和相关性。

创建一个提示词模板(prompt template)

可以使用 PromptTemplate 类创建简单的提示词。提示词模板可以内嵌任意数量的模板参数,然后通过参数值格式化模板内容。

1
2
3
4
5
6
7
8
from langchain.prompts import PromptTemplate

prompt_template = PromptTemplate.from_template(
    "Please translate {input_language} to {output_language}"
)

prompt = prompt_template.format(input_language="English", output_language="Chinese")
print(prompt)

聊天消息提示词模板(chat prompt template)

聊天提示词模板(Chat Prompt Template)是一种专门用于构建聊天机器人或多轮对话系统的提示词结构。它通过定义不同角色(如用户、助手、系统等)的消息格式,将对话内容组织成结构化的提示,以便语言模型能够更好地理解和生成连贯的对话。

与普通的提示词模板(Prompt Template)不同,聊天提示词模板通常包含多个消息模板,每个消息模板对应一个角色。例如:

  • 系统消息(System Message):用于定义聊天机器人的角色和行为准则。
  • 用户消息(Human Message):代表用户输入的内容。
  • 助手消息(AI Message):代表语言模型生成的回答。
1
2
3
4
5
6
7
8
9
10
11
12
13
from langchain.prompts import ChatPromptTemplate

chat_prompt_template = ChatPromptTemplate.from_messages(
    [
        ("system", "你是一名人工智能助手,你的名字是 {name}"),
        ("human", "你好!"),
        ("ai", "你好!"),
        ("human", "{user_input}")
    ]
)

chat_prompt = chat_prompt_template.format(name="Orchid", user_input="What's your name?")
print(chat_prompt)

另一种格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate
from langchain_core.messages import AIMessage, HumanMessage

chat_prompt_template = ChatPromptTemplate.from_messages(
    [
        SystemMessagePromptTemplate.from_template("你是一名人工智能助手,你的名字是 {name}"),
        HumanMessage(content="你好!"),
        AIMessage(content="你好!"),
        HumanMessagePromptTemplate.from_template("{user_input}")
    ]
)

chat_prompt = chat_prompt_template.format(name="Orchid", user_input="What's your name?")
print(chat_prompt)

response = tongyi_chat.invoke(chat_prompt)
print(response.content)

MessagesPlaceholder

在 LangChain 中,MessagesPlaceholder 是一个用于在聊天提示词模板(Chat Prompt Template)中预留消息占位符的工具。它的主要作用是在模板中动态插入一组消息(通常是对话历史),从而帮助语言模型更好地理解上下文并生成连贯的回复。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import AIMessage, HumanMessage

chat_prompt_template = ChatPromptTemplate.from_messages(
    [
        ("system", "你是一名人工智能助手,你的名字是 {name}"),
        MessagesPlaceholder(variable_name="history"),  # 预留消息占位符
        ("human", "{user_input}")
    ]
)

history = [
    HumanMessage(content="你好!"),
    AIMessage(content="你好!很高兴为你服务。"),
]

chat_prompt = chat_prompt_template.format(
    name="Orchid",
    history=history,
    user_input="What's your name?"
)
print(chat_prompt)