
LlamaIndex • 2025-03-20
使用 LlamaParse 解析 PDF:操作指南
生成式人工智能 (GenAI) 正在迅速而彻底地改变我们生产和消费信息的方式。但在数据方面,它是一个贪婪的“野兽”。
为了得出及时且相关的结论,它必须消耗大量准确的数据。驱动大部分 AI 的大型语言模型通常在公共网页上进行训练,因为它们资源丰富且易于访问。然而,并非所有信息都以 HTML 格式提供。
数百万个 Adobe PDF(便携式文档格式)文档包含事实、数据、方程式、法律法规等形式的数据,这些数据提取和存储后可能非常有用。将这些数据从 PDF 中提取出来可能是一个挑战。
LlamaIndex 的 LlamaParse 简化了从 PDF 中提取信息的过程。让我们向您展示如何通过几行代码来实现。
解析 PDF 的挑战
与 HTML 不同,HTML 本身为其呈现的内容提供了一些结构,而 PDF 最初是为了保留打印文档的视觉外观而创建的。尽管最终添加了编码结构元数据的能力,但这可能是一个繁琐的过程。
遗憾的是,生成包含结构元数据的 PDF 的应用程序常常出错。例如,Adobe InDesign 生成的 PDF 通常会根据设计师在页面上处理元素的顺序来设置页面的阅读顺序。
什么是 LlamaParse?
LlamaParse 是一个 GenAI 原生解析平台,用于解析和转换复杂文档,为 LLM 应用提供干净的数据。LlamaParse 集成了 LlamaIndex,这是一个开源数据编排框架,用于构建大型语言模型 (LLM) 应用。LlamaIndex 使构建代理及其支持的上下文数据变得更容易,它利用 AI 从多种文档格式中提取信息,包括 PDF。
LlamaParse 非常擅长
✅ 解析各种非结构化文件类型(.pdf、.pptx、.docx、.xlsx、.html、jpeg,以及更多)。
✅ 将内嵌表格准确解析为文本和半结构化表示。
✅ 从视觉元素(图像/图表)中提取数据。
✅ 使用自然语言指令按您需要的方式自定义输出。
使用 LlamaParse 进行 PDF 提取的好处
您可以自己解析 PDF,或使用标准的非 GenAI 启用的 PDF 解析器。然而,使用 LlamaParse 提供了许多改进
- 通过利用 LLM 智能减少数据提取中的手动工作,显著降低数据提取所需的时间和精力
- 通过从源文件中解放数据,增加 GenAI 应用可用数据的体量
- 将非结构化数据转换为结构化数据
使用 LlamaParse 从 PDF 中提取和存储信息
您可以通过我们的 UI (LlamaCloud)、API 或我们的语言 SDK 之一使用 LlamaParse。下面我们将使用 Python 演示 LlamaParse 的一些功能。如果您想尝试 LlamaParse 而无需编写代码,您可以创建免费的 LlamaCloud 账户并使用您自己的文档进行实验。
开始使用:安装 LlamaIndex 和 LlamaParse
首先,我们需要安装 LlamaIndex 和 LlamaParse,以便在我们的 Python 脚本中使用它们。
注意:建议在继续之前创建并激活一个虚拟 Python 环境,以避免因依赖版本冲突引起的问题。
pip install llama-index
pip install llama-parse
API 密钥
您还需要一个 API 密钥。要创建一个,请创建免费的 LlamaCloud 账户。

创建账户并登录后,点击左侧导航栏中的“API Keys”,然后点击“Generate New Key”按钮。

注意:一旦您的密钥显示,请复制并将其保存在安全位置。关闭屏幕后将无法再次显示。如果您的密钥丢失,应撤销并创建一个新的。
我们建议将您的 API 设置为 Python 虚拟环境中的环境变量。
export LLAMA_CLOUD_API_KEY='yourkey12345…."
现在我们准备开始解析 PDF 文件。让我们写一些代码。
使用 LlamaParse 和 Python 解析您的第一个 PDF
我们将首先解析一份两页的报告,比较纳斯达克 100 指数与标普 500 指数的投资回报。您可以使用浏览器或 wget 下载 PDF 文件。
wget https://indexes.nasdaqomx.com/docs/NDX-vs-SPX_2%20pager.pdf
现在我们将创建一个简单的 Python 脚本来解析 PDF 文件并将其内容保存为 markdown 格式。
from llama_parse import LlamaParse
parser = LlamaParse(
# api_key="llx-...", # if you did not create an environmental variable you can set the API key here
result_type="markdown", # "markdown" and "text" are available
)
file_name = "./NDX-vs-SPX_2 pager.pdf"
extra_info = {"file_name": file_name}
with open(f"./{file_name}", "rb") as f:
# must provide extra_info with file_name key with passing file object
documents = parser.load_data(f, extra_info=extra_info)
# with open('output.md', 'w') as f:
# print(documents, file=f)
# Write the output to a file
with open("output.md", "w", encoding="utf-8") as f:
for doc in documents:
f.write(doc.text)
将脚本保存为 parse.py,然后运行它。
python parse.py
脚本运行完成后,打开 output.md。您会看到 LlamaParse 成功地从 PDF 中提取了内容,并通过标题正确地应用了结构。请注意,第一页底部的表格也在 markdown 中重新创建了。
| |Nasdaq-100 TR|S&P 500 TR|
|---|---|---|
|Cumulative Return|315%|156%|
|Annualized Return|13%|9%|
|Annualized Volatility|22%|20%|
从图表和图形中提取数据
然而,您可能会注意到第一页上的两个图表中的数据缺失了。这实际上是设计使然。LlamaParse 支持多种解析模式,您可以根据当前的需求平衡速度、成本和高级解析能力。
上面使用的默认模式跳过了大多数图表,因为它们需要更高级和更昂贵的处理。但我们可以通过对解析器进行微小的配置更改,使 LlamaParse 使用不同的模式。
from llama_parse import LlamaParse
parser = LlamaParse(
# api_key="llx-...", # if you did not create an environmental variable you can set the API key here
result_type="markdown", # "markdown" and "text" are available,
extract_charts=True,
auto_mode=True,
auto_mode_trigger_on_image_in_page=True,
auto_mode_trigger_on_table_in_page=True,
)
file_name = "./NDX-vs-SPX_2 pager.pdf"
extra_info = {"file_name": file_name}
with open(f"./{file_name}", "rb") as f:
# must provide extra_info with file_name key with passing file object
documents = parser.load_data(f, extra_info=extra_info)
# with open('output.md', 'w') as f:
# print(documents, file=f)
# Write the output to a file
with open("output.md", "w", encoding="utf-8") as f:
for doc in documents:
f.write(doc.text)
当解析器完成其工作后,您会看到,例如,第二页上的行业细分图表已被解析并渲染为表格。
Industry (ICB) Breakdown
| Industry | Nasdaq-100 Industry (ICB) Weights | S&P 500 Industry (ICB) Weights |
|----------|-----------------------------------|--------------------------------|
| Technology | 55% | 22% |
| Consumer Services | 25% | 14% |
| Health Care | 8% | 13% |
| Consumer Goods | 6% | 8% |
| Industrials | 6% | 12% |
| Telecommunications | 1% | 2% |
| Utilities | 3% | 3% |
| Financials | - | 18% |
| Oil & Gas | - | 5% |
| Basic Materials | 2% | 2% |
了解更多关于解析模式的信息,以及 LlamaParse 自动模式如何使您能够在真正需要时才调用高级模式,从而优化解析成本。
将数据存储在向量数据库中
从 PDF 中提取数据后,您可以将其发送到向量数据库,例如 Elasticsearch。您需要来自OpenAI 和 Elastic Cloud 的 API 密钥,以及安装一些额外的依赖项,包括 nest_asyncio。从那里,只需几行额外的代码即可存储您的数据。
from llama_index.vector_stores.elasticsearch import ElasticsearchStore
es_store = ElasticsearchStore(
index_name="llama-parse-docs",
es_cloud_id=es_cloud_id, # found within the deployment page
es_api_key=es_api_key, # create an API key within Kibana (Security -> API Keys)
)
from llama_index.core.node_parser import SimpleNodeParser
node_parser = SimpleNodeParser()
nodes = node_parser.get_nodes_from_documents(documents)
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import VectorStoreIndex, StorageContext
storage_context = StorageContext.from_defaults(vector_store=es_store)
index = VectorStoreIndex(
nodes=nodes,
storage_context=storage_context,
embed_model=OpenAIEmbedding(api_key=openai_api_key),
)
我们在这里不会详细介绍整个过程,但我们在我们的仓库中准备了将提取的数据发送到 Elasticsearch 以及 发送到 Astra DB 的详细示例。
微调您的 PDF
几乎任何可以在电脑屏幕上显示的文档都可以保存为 PDF,正如我们之前讨论的,这使得一致地解析它们变得困难。LlamaParse 支持多种方法来调整提供给 LLM 的解析指令,以获得更好的结果或实现高级功能。
翻译您的输出
您有一个西班牙语文档,但需要将其内容存储为英语?LlamaParse 可以做到。
下载此西班牙语文档。
wget https://www.scusd.edu/sites/main/files/file-attachments/howtohelpyourchildsucceedinschoolspanish.pdf
LlamaParse 允许您自定义发送给启动解析的 LLM 的提示。
from llama_parse import LlamaParse
parser = LlamaParse(
result_type="markdown",
user_prompt="If the input is not in English, translate the output into English."
)
file_name = "./howtohelpyourchildsucceedinschoolspanish.pdf"
extra_info = {"file_name": file_name}
with open(f"./{file_name}", "rb") as f:
# must provide extra_info with file_name key with passing file object
documents = parser.load_data(f, extra_info=extra_info)
# with open('output.md', 'w') as f:
# print(documents, file=f)
# Write the output to a file
with open("output.md", "w", encoding="utf-8") as f:
for doc in documents:
f.write(doc.text)
提示功能强大无比,可为您提供对输出的精细控制。在文档中了解更多关于如何使用提示的信息。
限制/定向您的解析
如果您只需要解析 PDF 中的选定页面,您无需在解析前从源文件中提取这些页面。只需传递您希望解析的页面即可。
parser = LlamaParse(
target_pages="0,10,12,22-33"
)
请注意,页面编号从 0 开始。
如果您的源文件包含页眉或页脚,您可以指示 LlamaParse 忽略页面指定部分内的内容。这里我们指示解析器忽略页面顶部的 10% 和底部的 5%。
parser = LlamaParse(
bbox_top=0.1,
bbox_bottom=0.05
)
更多示例
您可以通过多种额外方式微调解析以满足您的特定需求。您可以应用输出模式来创建发票和简历。尽管我们重点介绍了 PDF 文件的解析,但 LlamaParse 支持从数十种不同的文件格式中提取数据,包括音频文件。
为了帮助您探索全部功能,我们整理了数十个示例,并已在我们的仓库中提供。
结论
LlamaParse 使解析 PDF 和其他非结构化数据比以往更容易、更省力。它呈指数级增加了 GenAI 应用可用的数据,同时解放了您的开发者,让他们能够专注于创新,而不是浪费时间编写定制应用来从难以处理的数据源中提取和解析数据。
立即开始使用 LlamaParse,每天免费解析多达 1000 页。