LlamaIndex中的提示使用模式
在LlamaIndex中,提示(prompts)是与语言模型(LLM)交互的关键部分。通过自定义提示,你可以更精确地控制模型的输出,以满足特定需求。本文将介绍如何在LlamaIndex中定义和使用自定义提示,以及一些高级提示功能。
定义自定义提示
定义自定义提示非常简单,只需创建一个格式字符串即可。以下是一个示例:
from llama_index.core import PromptTemplate
template = (
"We have provided context information below. \n"
"---------------------\n"
"{context_str}"
"\n---------------------\n"
"Given this information, please answer the question: {query_str}\n"
)
qa_template = PromptTemplate(template)
# 你可以创建文本提示(用于completion API)
prompt = qa_template.format(context_str=..., query_str=...)
# 或者轻松转换为消息提示(用于chat API)
messages = qa_template.format_messages(context_str=..., query_str=...)
注意:你可能会看到对诸如QuestionAnswerPrompt、RefinePrompt等旧版提示子类的引用。这些已被弃用(现在是PromptTemplate的类型别名)。现在你可以直接指定PromptTemplate(template)
来构造自定义提示。但仍需确保模板字符串包含预期的参数(例如{context_str}
和{query_str}
)。
你还可以从聊天消息定义模板:
from llama_index.core import ChatPromptTemplate
from llama_index.core.llms import ChatMessage, MessageRole
message_templates = [
ChatMessage