主题
LlamaIndex 是我们用于构建智能体与检索增强生成(RAG)的开源 Python 工具箱。它内置的 reader 处理干净文本很好;而对扫描件 PDF、表单、电子表格与幻灯片,请先跑一个 Parse 任务再把结果交给框架 —— 进了索引的东西质量如何,决定了它给出的每个答案的质量。
两个产品用同一个 API key。在环境里设好 LLAMA_CLOUD_API_KEY,然后安装这两个包:
终端窗口
pip install llama-index "llama-cloud>=2.8"
export LLAMA_CLOUD_API_KEY=llx-...用 Parse 输出构建索引
先把美国财政部 FY2024 财报的执行摘要下载为 data/report.pdf:
终端窗口
curl -fL --create-dirs -o data/report.pdf https://fiscal.treasury.gov/system/files/files/reports-statements/financial-report/2024/executive-summary-2024.pdfparsing.parse() 会上传文件、等任务结束并返回结果。带上 expand=["markdown"] 时,结果会为每页携带一段 Markdown 字符串。把每页包成框架的 Document,之后与处理任何文本一样建索引:
from llama_cloud import LlamaCloud
from llama_index.core import Document, VectorStoreIndex
client = LlamaCloud() # reads LLAMA_CLOUD_API_KEY
file = client.files.create(file="data/report.pdf", purpose="parse")
result = client.parsing.parse(
file_id=file.id, tier="agentic", version="latest", expand=["markdown"]
)
pages = result.markdown.pages
documents = [
Document(text=p.markdown, metadata={"page": p.page_number})
for p in pages
if p.success
]
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
response = query_engine.query("What does this document say about pricing?")
print(response)解析失败的页会以 success 为 False、且不带 Markdown 的形式返回,这就是那段推导式要按它过滤的原因。把页号留在 metadata 里,检索结果就能指回它来自哪一页。
同样的写法适用于一个目录里的多个文件:每个文件跑一个 Parse 任务,收集这些文档,再建一个索引。集合更大时,Index 会让索引与数据源保持同步并通过 API 提供检索,本地无需重建任何东西。
在智能体里使用 Extract 输出
Extract 按你的 schema 返回 JSON。框架的智能体可以把它当工具调用,于是由智能体自己决定何时从文档里取出结构化数据:
from llama_cloud import LlamaCloud
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI
client = LlamaCloud()
def extract_invoice(path: str) -> dict:
"""Extract vendor, invoice number, date and total from an invoice file."""
file = client.files.create(file=path, purpose="extract")
job = client.extract.run( # creates the job and waits for it to finish
file_input=file.id,
configuration={
"data_schema": {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"invoice_number": {"type": "string"},
"date": {"type": "string"},
"total": {"type": "number"},
},
}
},
)
return job.extract_result
agent = FunctionAgent(
tools=[extract_invoice],
llm=OpenAI(model="gpt-4.1-mini"),
system_prompt="You answer questions about invoices by extracting their fields.",
)schema 选项见Extract 快速上手,智能体那一侧见构建智能体。
该在哪里跑解析
| 需求 | 该用什么 |
|---|---|
| 干净的文本文件、Markdown、HTML | 框架内置的 reader |
| 本地解析、不要 API key | LiteParse,开源解析器 |
| 扫描件、表格、图表、表单、130+ 格式 | Parse,如上所述 |
| 从文档里取结构化字段 | Extract,如上所述 |
| 一个与数据源保持同步的托管索引 | Index |