17 LlamaIndex中的提示使用模式

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(content="You are an expert system.", role=MessageRole.SYSTEM),
    ChatMessage(
        content="Generate a short story about {topic}",
        role=MessageRole.USER,
    ),
]
chat_template = ChatPromptTemplate(message_templates=message_templates)

# 你可以创建消息提示(用于chat API)
messages = chat_template.format_messages(topic=...)

# 或者轻松转换为文本提示(用于completion API)
prompt = chat_template.format(topic=...)

获取和设置自定义提示

由于LlamaIndex是一个多步骤的管道,因此识别你想要修改的操作并在正确的地方传递自定义提示非常重要。

例如,提示用于响应合成器、检索器、索引构建等;其中一些模块嵌套在其他模块中(合成器嵌套在查询引擎中)。

请参阅此指南以获取访问/自定义提示的完整详细信息。

常用提示

最常用的提示是text_qa_templaterefine_template

  • text_qa_template - 用于使用检索到的节点获取查询的初始答案
  • refine_template - 当检索到的文本不能在一个LLM调用中使用response_mode="compact"(默认)时,或者当使用response_mode="refine"检索到多个节点时使用。第一个查询的答案作为existing_answer插入,LLM必须根据新上下文更新或重复现有答案。

访问提示

你可以在LlamaIndex的许多模块上调用get_prompts来获取模块及其嵌套子模块中使用的提示的平面列表。

例如,查看以下代码片段:

query_engine = index.as_query_engine(response_mode="compact")
prompts_dict = query_engine.get_prompts()
print(list(prompts_dict.keys()))

你可能会得到以下键:

['response_synthesizer:text_qa_template', 'response_synthesizer:refine_template']

注意,提示以其子模块为“命名空间”作为前缀。

更新提示

你可以在任何实现了get_prompts的模块上使用update_prompts函数自定义提示。只需传递键等于通过get_prompts获得的提示字典中的键的参数值。

例如,关于上面的示例,我们可以这样做:

# 莎士比亚风格!
qa_prompt_tmpl_str = (
    "Context information is below.\n"
    "---------------------\n"
    "{context_str}\n"
    "---------------------\n"
    "Given the context information and not prior knowledge, "
    "answer the query in the style of a Shakespeare play.\n"
    "Query: {query_str}\n"
    "Answer: "
)
qa_prompt_tmpl = PromptTemplate(qa_prompt_tmpl_str)

query_engine.update_prompts(
    {"response_synthesizer:text_qa_template": qa_prompt_tmpl}
)

修改查询引擎中使用的提示

对于查询引擎,你也可以在查询时直接传递自定义提示(即在对索引执行查询并合成最终响应时)。

有两种等效的方法可以覆盖提示:

  1. 通过高级API
query_engine = index.as_query_engine(
    text_qa_template=custom_qa_prompt, refine_template=custom_refine_prompt
)
  1. 通过低级组合API
retriever = index.as_retriever()
synth = get_response_synthesizer(
    text_qa_template=custom_qa_prompt, refine_template=custom_refine_prompt
)
query_engine = RetrieverQueryEngine(retriever, response_synthesizer)

以上两种方法等效,其中1是2的语法糖,隐藏了底层复杂性。你可能想使用1快速修改一些常见参数,使用2进行更细粒度的控制。

有关哪些类使用哪些提示的更多详细信息,请访问查询类参考。

查看参考文档以获取所有提示的完整集合。

修改索引构建中使用的提示

一些索引在构建过程中使用不同类型的提示(注意:最常见的VectorStoreIndex和SummaryIndex不使用任何提示)。

例如,TreeIndex使用摘要提示来层次化总结节点,KeywordTableIndex使用关键词提取提示来提取关键词。

有两种等效的方法可以覆盖提示:

  1. 通过默认节点构造函数
index = TreeIndex(nodes, summary_template=custom_prompt)
  1. 通过文档构造函数
index = TreeIndex.from_documents(docs, summary_template=custom_prompt)

有关哪些索引使用哪些提示的更多详细信息,请访问索引类参考。

[高级] 高级提示功能

在本节中,我们将展示LlamaIndex中的一些高级提示功能。

相关指南:

  • 高级提示
  • RAG的提示工程

部分格式化

部分格式化提示,填充一些变量,同时保留其他变量稍后填充。

from llama_index.core import PromptTemplate

prompt_tmpl_str = "{foo} {bar}"
prompt_tmpl = PromptTemplate(prompt_tmpl_str)
partial_prompt_tmpl = prompt_tmpl.partial_format(foo="abc")

fmt_str = partial_prompt_tmpl.format(bar="def")

模板变量映射

LlamaIndex提示抽象通常期望某些键。例如,我们的text_qa_prompt期望context_str作为上下文,query_str作为用户查询。

但如果你试图适应一个字符串模板以用于LlamaIndex,更改模板变量可能会很烦人。

相反,定义template_var_mappings

template_var_mappings = {"context_str": "my_context", "query_str": "my_query"}

prompt_tmpl = PromptTemplate(
    qa_prompt_tmpl_str, template_var_mappings=template_var_mappings
)

函数映射

将函数作为模板变量传递,而不是固定值。

这是一个非常高级且强大的功能;允许你进行动态少样本提示等。

以下是一个重新格式化context_str的示例:

def format_context_fn(**kwargs):
    # 使用项目符号格式化上下文
    context_list = kwargs["context_str"].split("\n\n")
    fmtted_context = "\n\n".join([f"- {c}" for c in context_list])
    return fmtted_context

prompt_tmpl = PromptTemplate(
    qa_prompt_tmpl_str, function_mappings={"context_str": format_context_fn}
)

prompt_tmpl.format(context_str="context", query_str="query")

通过这些高级提示功能,你可以更灵活地控制LlamaIndex与LLM的交互,从而实现更复杂和定制化的应用需求。

  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Llamaindex是一个开源的搜索引擎,可以用于快速搜索和索引大型数据集。为了在本地部署Llamaindex,您需要按照以下步骤进行操作。 首先,您需要从Llamaindex的官方GitHub页面上下载源代码。确保您的计算机已安装了Git系统,然后使用命令行工具输入以下命令来克隆代码库: ``` git clone https://github.com/llama-lab/llamaindex.git ``` 下载完成后,进入项目文件夹并创建一个Python虚拟环境。使用以下命令可以创建一个虚拟环境: ``` python3 -m venv llama-env ``` 然后需要激活虚拟环境。在Mac和Linux系统下,使用以下命令: ``` source llama-env/bin/activate ``` 在Windows系统下,使用以下命令: ``` llama-env\Scripts\activate ``` 接下来,安装Llamaindex的依赖项。在虚拟环境运行以下命令: ``` pip install -r requirements.txt ``` 等待依赖项安装完成后,可以开始配置Llamaindex。编辑`config.yaml`文件,根据您的需求进行相应的修改。您可以设置数据集的路径、索引文件的位置和其他相关参数。 完成配置后,运行以下命令来创建索引: ``` python3 llama.py -f path/to/dataset ``` 上述命令的`path/to/dataset`应替换为实际的数据集路径。运行该命令后,Llamaindex会开始索引数据集。 当索引完成后,您可以使用以下命令来搜索索引的数据: ``` python3 llama.py -s "your search query" ``` 您可以将`"your search query"`替换为实际的搜索关键字。Llamaindex将返回与关键字匹配的结果。 以上就是在本地部署Llamaindex的步骤。祝您在使用Llamaindex时取得成功!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要重新演唱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值