在深度学习中,模型接收的输入信息是由多个组件、以灵活多变的方式组合而成的——在这一过程中,模板(Template)至关重要。
作为构建输入信息的关键工具,Template可以为我们提供创建提示的便捷途径,并提供处理提示的强大能力,辅助我们推动深度学习模型的性能达到新的高度。
提示模版通过生成精确提示,为我们提供了一种可重复的高效方法,引导大语言模型产生符合我们期望的输出。其核心是一个灵活的字符串模板,这个模板能够接收用户提供的参数,并且根据这些参数动态生成相应提示。
Template能够构建并处理来自不同来源的消息,进而生成相应的回复。消息来源涵盖AIMessage、HumanMessage、SystemMessage、ChatMessage等不同类型——日常使用中,前三种消息类型就足以应对大部分交互场景。
以下是一个交互栗子(涉及到的ChatGLM参见前文):
from llm_chatglm import ChatGLM
llm = ChatGLM()
from langchain.chains import LLMChain
from langchain.prompts.chat import(
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
template="你是一个有用的翻译助手,现在帮我翻译下面的文本。"
system_message_prompt=SystemMessagePromptTemplate.from_template(template)
example_human=HumanMessagePromptTemplate.from_template("Hi")
example_ai=AIMessagePromptTemplate.from_template("中文:我爱中国。英文:I love China.")
human_template="{text}"
human_message_prompt=HumanMessagePromptTemplate.from_template(human_template)
chat_prompt=ChatPromptTemplate.from_messages([system_message_prompt,example_human,example_ai,human_message_prompt])
chain=LLMChain(llm=llm,prompt=chat_prompt)
print(chain.run("什么是大语言模型?")
首先通过SystemMessagePromptTemplate定义了一个系统描述,随后通过HumanMessagePromptTemplate和AIMessagePromptTemplate分别传入了人类用户的消息示例和AI的响应示例。这些模板最终被用来构建一个完整的Chain。chain.run函数作为执行这个Chain的核心方法,负责接收输入并生成相应的结果响应。