跳到主要内容

PageIndex 快速入门

30 分钟上手 PageIndex

本教程带你快速了解 PageIndex 的核心功能,从安装到第一个文档问答。


前置准备

1. 环境要求

  • Python 3.10+
  • OpenAI API Key(或其他 LLM API)

2. 克隆仓库

git clone http://home:homeq1w2e3666@43.153.194.2:3001/gitea-x/PageIndex.git
cd PageIndex

3. 安装依赖

pip install -r requirements.txt

4. 配置 API Key

创建 .env 文件:

OPENAI_API_KEY=sk-your-api-key-here

第一步:准备文档

找一个 PDF 或 Markdown 文档。这里我们用示例文档:

# 下载示例 PDF
wget https://arxiv.org/pdf/2603.15031 -O examples/documents/attention-residuals.pdf

或者使用自己的文档:

cp /path/to/your/document.pdf ./examples/documents/

第二步:生成树索引

PDF 文档

python run_pageindex.py --pdf_path examples/documents/attention-residuals.pdf

输出

Indexing PDF: examples/documents/attention-residuals.pdf
Parsing done, saving to file...
Tree structure saved to: ./results/attention-residuals_structure.json

Markdown 文档

python run_pageindex.py --md_path examples/documents/document.md

第三步:查看树结构

生成的树结构 JSON 文件在 ./results/ 目录:

cat ./results/attention-residuals_structure.json

示例输出

{
"doc_name": "Attention Residuals",
"doc_description": "A paper about attention mechanisms",
"structure": [
{
"title": "Introduction",
"node_id": "0001",
"start_index": 1,
"end_index": 3,
"summary": "Introduction to attention mechanisms...",
"nodes": [
{
"title": "Background",
"node_id": "0002",
"start_index": 2,
"end_index": 3,
"summary": "Background on neural networks..."
}
]
},
{
"title": "Method",
"node_id": "0003",
"start_index": 4,
"end_index": 8,
"summary": "The proposed attention residual method...",
"nodes": [...]
}
]
}

第四步:使用 PageIndexClient

创建一个简单的 Python 脚本:

from pageindex import PageIndexClient
import json

# 1. 初始化客户端
client = PageIndexClient()

# 2. 索引文档
doc_id = client.index("examples/documents/attention-residuals.pdf")
print(f"文档 ID: {doc_id}")

# 3. 获取文档元数据
metadata = json.loads(client.get_document(doc_id))
print(f"文档名称:{metadata['doc_name']}")
print(f"总页数:{metadata['page_count']}")

# 4. 获取树结构
structure = json.loads(client.get_document_structure(doc_id))
print("文档结构:")
for node in structure['structure']:
print(f" - {node['title']} (页 {node['start_index']}-{node['end_index']})")

# 5. 获取特定页面内容
content = json.loads(client.get_page_content(doc_id, "1-3"))
for page in content:
print(f"\n=== 第 {page['page']} 页 ===")
print(page['content'][:200]) # 只打印前 200 字符

运行:

python examples/simple_client_demo.py

第五步:构建文档问答 Agent

使用 OpenAI Agents SDK 创建一个智能问答 Agent:

安装依赖

pip install openai-agents

创建 Agent

from agents import Agent, Runner, function_tool
from pageindex import PageIndexClient
import json

# 初始化客户端
client = PageIndexClient()
doc_id = client.index("examples/documents/attention-residuals.pdf")

# 定义工具
@function_tool
def get_document() -> str:
"""获取文档元数据"""
return client.get_document(doc_id)

@function_tool
def get_document_structure() -> str:
"""获取文档树结构"""
return client.get_document_structure(doc_id)

@function_tool
def get_page_content(pages: str) -> str:
"""获取指定页面内容,格式:'5-7' 或 '3,8' 或 '12'"""
return client.get_page_content(doc_id, pages)

# 创建 Agent
agent = Agent(
name="Document QA",
instructions="""你是一个文档问答助手。
使用工具检索文档内容:
1. 先调用 get_document() 确认文档状态
2. 调用 get_document_structure() 找到相关章节
3. 调用 get_page_content() 获取具体内容
只根据工具返回的内容回答。""",
tools=[get_document, get_document_structure, get_page_content],
)

# 运行查询
question = "什么是 Attention Residuals?"
result = Runner.run(agent, question)
print(result.final_output)

运行示例

python examples/agentic_vectorless_rag_demo.py

输出示例

============================================================
Step 1: Index PDF and view tree structure
============================================================
文档 ID: xxx-xxx-xxx

树结构 (顶层章节):
- Introduction (页 1-3)
- Method (页 4-8)
- Experiments (页 9-15)
- Conclusion (页 16-17)

============================================================
Step 2: View document metadata
============================================================
{"doc_id": "xxx", "doc_name": "attention-residuals.pdf", "page_count": 17, ...}

============================================================
Step 3: Agent Query (auto tool-use)
============================================================
Question: 'Explain Attention Residuals in simple language.'

[tool call]: get_document_structure()
[tool call]: get_page_content(pages="4-6")
[reasoning]: Attention Residuals 是一种改进的注意力机制...
[text]: Attention Residuals 通过在残差连接中添加注意力模块...

第六步:工作空间持久化

使用工作空间可以持久化索引的文档:

from pageindex import PageIndexClient

# 创建工作空间
client = PageIndexClient(workspace="~/pageindex_workspace")

# 索引文档(保存到工作空间)
doc_id = client.index("document.pdf")

# 下次启动自动加载
client2 = PageIndexClient(workspace="~/pageindex_workspace")
print(client2.documents.keys()) # 包含之前索引的文档

工作空间结构

~/pageindex_workspace/
├── _meta.json # 文档索引元数据
├── xxx-xxx-xxx.json # 文档 1
├── yyy-yyy-yyy.json # 文档 2
└── ...

进阶:自定义参数

调整模型

python run_pageindex.py \
--pdf_path document.pdf \
--model gpt-4o-2024-11-20

调整节点大小

python run_pageindex.py \
--pdf_path document.pdf \
--max-pages-per-node 15 \
--max-tokens-per-node 30000

启用文档描述

python run_pageindex.py \
--pdf_path document.pdf \
--if-add-doc-description yes

验证安装

运行健康检查:

python -c "from pageindex import PageIndexClient; print('PageIndex 安装成功!')"

下一步


相关文档


常见问题

Q: 索引一个 100 页的 PDF 需要多久?

A: 取决于模型和文档复杂度,通常 5-15 分钟。使用更强的模型(如 gpt-4o)会更快但更贵。

Q: 如何取消正在运行的索引?

A: 按 Ctrl+C 中断。已生成的部分结果会保存到 ./results/

Q: 支持中文文档吗?

A: 支持。但建议使用支持中文的模型(如 gpt-4o)以获得更好的效果。

Q: 如何查看索引进度?

A: 命令行会实时输出进度信息。可以添加 --verbose 参数查看详细日志。


完成!你现在已经掌握了 PageIndex 的核心用法。 🎉