结构化 LLM 重排器演示 (2021 Lyft 10-k)¶
本教程展示了如何进行两阶段检索。使用具有高 top-k 值的基于嵌入的检索,以最大化召回率并获得大量候选项目。然后,使用基于 LLM 的检索,利用结构化输出动态选择与查询实际相关的节点。
当您使用支持函数调用的模型时,优先使用 StructuredLLMReranker
而不是 LLMReranker
。此类将利用模型的结构化输出能力,而不是依赖于提示模型以所需格式对节点进行排名。
In [ ]
已复制!
%pip install llama-index-llms-openai
%pip install llama-index-llms-openai
In [ ]
已复制!
import nest_asyncio
nest_asyncio.apply()
import nest_asyncio nest_asyncio.apply()
In [ ]
已复制!
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.core.postprocessor import StructuredLLMRerank
from llama_index.llms.openai import OpenAI
from IPython.display import Markdown, display
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.postprocessor import StructuredLLMRerank from llama_index.llms.openai import OpenAI from IPython.display import Markdown, display
下载数据¶
In [ ]
已复制!
!mkdir -p 'data/10k/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/10k/lyft_2021.pdf' -O 'data/10k/lyft_2021.pdf'
!mkdir -p 'data/10k/' !wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/10k/lyft_2021.pdf' -O 'data/10k/lyft_2021.pdf'
--2025-03-20 15:13:23-- https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/10k/lyft_2021.pdf Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.108.133, 185.199.110.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1440303 (1.4M) [application/octet-stream] Saving to: ‘data/10k/lyft_2021.pdf’ data/10k/lyft_2021. 100%[===================>] 1.37M --.-KB/s in 0.06s 2025-03-20 15:13:24 (23.9 MB/s) - ‘data/10k/lyft_2021.pdf’ saved [1440303/1440303]
加载数据,构建索引¶
In [ ]
已复制!
from llama_index.core import Settings
# LLM (gpt-4o-mini)
Settings.llm = OpenAI(temperature=0, model="gpt-4o-mini")
Settings.chunk_overlap = 0
Settings.chunk_size = 128
from llama_index.core import Settings # LLM (gpt-4o-mini) Settings.llm = OpenAI(temperature=0, model="gpt-4o-mini") Settings.chunk_overlap = 0 Settings.chunk_size = 128
In [ ]
已复制!
# load documents
documents = SimpleDirectoryReader(
input_files=["./data/10k/lyft_2021.pdf"]
).load_data()
# 加载文档 documents = SimpleDirectoryReader( input_files=["./data/10k/lyft_2021.pdf"] ).load_data()
In [ ]
已复制!
index = VectorStoreIndex.from_documents(
documents,
)
index = VectorStoreIndex.from_documents( documents, )
检索比较¶
In [ ]
已复制!
from llama_index.core.retrievers import VectorIndexRetriever
from llama_index.core import QueryBundle
import pandas as pd
from IPython.display import display, HTML
from copy import deepcopy
def get_retrieved_nodes(
query_str, vector_top_k=10, reranker_top_n=3, with_reranker=False
):
query_bundle = QueryBundle(query_str)
# configure retriever
retriever = VectorIndexRetriever(
index=index,
similarity_top_k=vector_top_k,
)
retrieved_nodes = retriever.retrieve(query_bundle)
if with_reranker:
# configure reranker
reranker = StructuredLLMRerank(
choice_batch_size=5,
top_n=reranker_top_n,
)
retrieved_nodes = reranker.postprocess_nodes(
retrieved_nodes, query_bundle
)
return retrieved_nodes
def pretty_print(df):
return display(HTML(df.to_html().replace("\\n", "<br>")))
def visualize_retrieved_nodes(nodes) -> None:
result_dicts = []
for node in nodes:
node = deepcopy(node)
node.node.metadata = {}
node_text = node.node.get_text()
node_text = node_text.replace("\n", " ")
result_dict = {"Score": node.score, "Text": node_text}
result_dicts.append(result_dict)
pretty_print(pd.DataFrame(result_dicts))
from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core import QueryBundle import pandas as pd from IPython.display import display, HTML from copy import deepcopy def get_retrieved_nodes( query_str, vector_top_k=10, reranker_top_n=3, with_reranker=False ): query_bundle = QueryBundle(query_str) # 配置检索器 retriever = VectorIndexRetriever( index=index, similarity_top_k=vector_top_k, ) retrieved_nodes = retriever.retrieve(query_bundle) if with_reranker: # 配置重排器 reranker = StructuredLLMRerank( choice_batch_size=5, top_n=reranker_top_n, ) retrieved_nodes = reranker.postprocess_nodes( retrieved_nodes, query_bundle ) return retrieved_nodes def pretty_print(df): return display(HTML(df.to_html().replace("\\n", "
"))) def visualize_retrieved_nodes(nodes) -> None: result_dicts = [] for node in nodes: node = deepcopy(node) node.node.metadata = {} node_text = node.node.get_text() node_text = node_text.replace("\n", " ") result_dict = {"得分": node.score, "文本": node_text} result_dicts.append(result_dict) pretty_print(pd.DataFrame(result_dicts))
"))) def visualize_retrieved_nodes(nodes) -> None: result_dicts = [] for node in nodes: node = deepcopy(node) node.node.metadata = {} node_text = node.node.get_text() node_text = node_text.replace("\n", " ") result_dict = {"得分": node.score, "文本": node_text} result_dicts.append(result_dict) pretty_print(pd.DataFrame(result_dicts))
In [ ]
已复制!
new_nodes = get_retrieved_nodes(
"What is Lyft's response to COVID-19?", vector_top_k=5, with_reranker=False
)
new_nodes = get_retrieved_nodes( "What is Lyft's response to COVID-19?", vector_top_k=5, with_reranker=False )
In [ ]
已复制!
visualize_retrieved_nodes(new_nodes)
visualize_retrieved_nodes(new_nodes)
得分 | 文本 | |
---|---|---|
0 | 0.870327 | 此外,COVID-19 已经并将可能继续对 Lyft 通过 Express Drive 项目和 Lyft Rentals 进行租赁运营的能力产生负面影响,这是由于旅行限制、强制关闭、人员配备有限以及与 COVID-19 相关的其他因素造成的。例如,在 2020 年,由于 COVID-19,Lyft Rentals 暂时停止运营,关闭了其租赁地点。 |
1 | 0.858815 | 公司已采取多项措施应对 COVID-19 大流行,包括但不限于为网约车制定新的健康和安全要求以及更新工作场所政策。公司还调整了支出和现金流,使其与收入下降相对应,包括 2020 年的裁员。有关 2020 年重组事件的信息,请参阅合并财务报表附注 17“重组”。 |
2 | 0.857701 | •应对 COVID-19 大流行的措施已导致我们修改了业务实践,允许我们几乎所有地点的公司员工远程工作,限制员工旅行,并取消、推迟或举办虚拟活动和会议。 |
3 | 0.855108 | 目前无法估计这些挑战的强度和持续时间。为应对 COVID-19 大流行,我们已采取多项措施,包括但不限于为网约车制定新的健康和安全要求以及更新工作场所政策。我们还调整了支出和现金流,使其与收入下降相对应,包括 2020 年的裁员。 |
4 | 0.854779 | 在 2020 年,Flexdrive 还开始免除经确认 COVID-19 检测呈阳性或被医疗专业人员要求隔离的司机的租金,目前仍继续执行此政策。此外,Lyft Rentals 和 Flexdrive 在运输、收回、清洁等方面面临更高的成本,以及17 |
In [ ]
已复制!
new_nodes = get_retrieved_nodes(
"What is Lyft's response to COVID-19?",
vector_top_k=20,
reranker_top_n=5,
with_reranker=True,
)
new_nodes = get_retrieved_nodes( "What is Lyft's response to COVID-19?", vector_top_k=20, reranker_top_n=5, with_reranker=True, )
In [ ]
已复制!
visualize_retrieved_nodes(new_nodes)
visualize_retrieved_nodes(new_nodes)
得分 | 文本 | |
---|---|---|
0 | 10.0 | 公司已采取多项措施应对 COVID-19 大流行,包括但不限于为网约车制定新的健康和安全要求以及更新工作场所政策。公司还调整了支出和现金流,使其与收入下降相对应,包括 2020 年的裁员。有关 2020 年重组事件的信息,请参阅合并财务报表附注 17“重组”。 |
1 | 10.0 | 我们已采取多项措施应对 COVID-19 大流行,包括但不限于为网约车制定新的健康和安全要求,以及更新工作场所政策。我们还调整了支出和现金流,使其与收入下降相对应,包括与 Woven Planet 于 2021 年 7 月 13 日完成的交易以及 2020 年的裁员。 |
2 | 10.0 | •根据 COVID-19 大流行和各司法管辖区发布的公共卫生措施(包括旅行禁令、旅行限制和居家隔离令)管理我们的平台、业务资产和费用,并在 COVID-19 大流行期间及之后保持对我们平台安全性的需求和信心;•规划和管理我们当前和未来产品的资本支出, |
3 | 9.0 | 目前无法估计这些挑战的强度和持续时间。为应对 COVID-19 大流行,我们已采取多项措施,包括但不限于为网约车制定新的健康和安全要求以及更新工作场所政策。我们还调整了支出和现金流,使其与收入下降相对应,包括 2020 年的裁员。 |
4 | 9.0 | 目前无法估计这些挑战的强度和持续时间。为应对 COVID-19 大流行,我们已采取多项措施,包括但不限于为网约车制定新的健康和安全要求以及更新工作场所政策。我们还调整了支出和现金流,使其与收入下降相对应,包括 2020 年的裁员。56 |
In [ ]
已复制!
new_nodes = get_retrieved_nodes(
"What initiatives are the company focusing on independently of COVID-19?",
vector_top_k=5,
with_reranker=False,
)
new_nodes = get_retrieved_nodes( "What initiatives are the company focusing on independently of COVID-19?", vector_top_k=5, with_reranker=False, )
In [ ]
已复制!
visualize_retrieved_nodes(new_nodes)
visualize_retrieved_nodes(new_nodes)
得分 | 文本 | |
---|---|---|
0 | 0.813871 | •应对 COVID-19 大流行的措施已导致我们修改了业务实践,允许我们几乎所有地点的公司员工远程工作,限制员工旅行,并取消、推迟或举办虚拟活动和会议。 |
1 | 0.810687 | •根据 COVID-19 大流行和各司法管辖区发布的公共卫生措施(包括旅行禁令、旅行限制和居家隔离令)管理我们的平台、业务资产和费用,并在 COVID-19 大流行期间及之后保持对我们平台安全性的需求和信心;•规划和管理我们当前和未来产品的资本支出, |
2 | 0.809540 | 目前无法估计这些挑战的强度和持续时间。为应对 COVID-19 大流行,我们已采取多项措施,包括但不限于为网约车制定新的健康和安全要求以及更新工作场所政策。我们还调整了支出和现金流,使其与收入下降相对应,包括 2020 年的裁员。 |
3 | 0.806794 | 支持我们开发平台的支出时机和程度,我们已拨备的实际保险赔付,我们为应对 COVID-19 大流行采取的措施,我们在 COVID-19 大流行期间及之后维持对我们平台安全性的需求和信心的能力,以及销售和营销活动的扩展。 |
4 | 0.805533 | •预测和应对宏观经济变化以及我们运营市场的变化;•维护和提升我们的声誉和品牌价值;•有效管理我们的增长和业务运营,包括 COVID-19 大流行对我们业务的影响;•成功扩大我们的地理覆盖范围;•招聘、整合和留住组织各层级的优秀人才;•成功开发新的平台功能、产品和服务,以增强用户体验;以及•优化我们的房地产组合规模。 |
In [ ]
已复制!
new_nodes = get_retrieved_nodes(
"What initiatives are the company focusing on independently of COVID-19?",
vector_top_k=40,
reranker_top_n=5,
with_reranker=True,
)
new_nodes = get_retrieved_nodes( "What initiatives are the company focusing on independently of COVID-19?", vector_top_k=40, reranker_top_n=5, with_reranker=True, )
In [ ]
已复制!
visualize_retrieved_nodes(new_nodes)
visualize_retrieved_nodes(new_nodes)
得分 | 文本 | |
---|---|---|
0 | 9.0 | 即使我们对业务进行投资,我们也仍然专注于寻找提高运营效率的方法。为了推进我们的使命,我们的目标是打造代表我们这一代人的标志性品牌,并通过我们对社会和环境责任的承诺进行倡导。我们相信我们的品牌代表着触手可及的自由:摆脱拥车烦恼的自由,以及做更多、看更多的自由。 |
1 | 8.0 | 我们还投资于销售和营销,以发展我们的社区,培养与司机和乘客产生共鸣的差异化品牌,并进一步提升品牌知名度。总而言之,这些投资使我们能够创建一个强大的多模态平台和规模化的用户网络。尽管受到 COVID-19 的影响,我们仍在继续投资于未来,无论是通过有机增长还是通过收购互补业务。 |
2 | 8.0 | 因此,我们可能会对现有产品进行重大更改,或开发和推出新的、未经证实的产品。例如,在 2020 年 4 月,我们开始试行一个配送服务平台,以应对 COVID-19 大流行。 |
3 | 6.0 | •预测和应对宏观经济变化以及我们运营市场的变化;•维护和提升我们的声誉和品牌价值;•有效管理我们的增长和业务运营,包括 COVID-19 大流行对我们业务的影响;•成功扩大我们的地理覆盖范围;•招聘、整合和留住组织各层级的优秀人才;•成功开发新的平台功能、产品和服务,以增强用户体验;以及•优化我们的房地产组合规模。 |
4 | 6.0 | 对于我们的成功至关重要。我们面临一些可能影响我们维持企业文化的挑战,包括:•未能识别、吸引、奖励和留住认同并推进我们文化、价值观和使命的组织领导层人才;•我们员工队伍规模不断扩大且地理分布日益多样化;•我们在某些运营司法管辖区的居家隔离令要求我们的许多员工远程工作, |