Skip to content
LlamaParse 文档版本 跟随上游 源快照 26f4d8a2 更新于 2026-10-16

用 Parse 处理单个 PDF,并理解最常见的四种输出视图:text、markdown、items 与 metadata。本例用的是财政服务局 2024 年执行摘要

1. 准备并连接 Parse

首先把 API key 设成环境变量,SDK 与 CLI 都会自动读取:

终端窗口

export LLAMA_CLOUD_API_KEY="llx-..."

然后安装你所用语言的 SDK 并初始化一个 client:

  • Python
  • TypeScript
  • Go
  • Java
  • CLI

终端窗口

pip install "llama-cloud>=2.8"
from llama_cloud import LlamaCloud

client = LlamaCloud()  # reads LLAMA_CLOUD_API_KEY from the environment

终端窗口

npm install @llamaindex/llama-cloud
import LlamaCloud from '@llamaindex/llama-cloud';

const client = new LlamaCloud(); // reads LLAMA_CLOUD_API_KEY from the environment

终端窗口

go get github.com/run-llama/llama-parse-go
import (
  "context"

  llamacloud "github.com/run-llama/llama-parse-go"
)

ctx := context.Background()
client := llamacloud.NewClient() // reads LLAMA_CLOUD_API_KEY from the environment
implementation("ai.llamaindex:llama-cloud:1.3.0")
import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;

// reads LLAMA_CLOUD_API_KEY from the environment
LlamaCloudClient client = LlamaCloudOkHttpClient.fromEnv();

终端窗口

go install github.com/run-llama/llama-parse-cli/cmd/llp@latest

llp 会从环境里读取 LLAMA_CLOUD_API_KEY(也可在任意命令上加 --api-key 传入)。

2. 上传并解析一个 PDF

解析之前,我们先用一个 client 连接 Parse,并选一个档位。档位决定 Parse 在质量/延迟/成本之间的取舍:

  • “fast” - 最快的档位,只有基础解析能力。
  • “cost_effective” – 对较简单的文档成本与延迟更低。
  • “agentic” – 多数场景的默认档位。
  • “agentic_plus” – 面对极复杂版式时保真度最高。

接着我们上传 PDF 并解析它
expand 参数告诉 Parse 要把哪些输出视图内联在任务结果里一并返回。本例请求的是:

  • “text” – 逐页纯文本
  • “markdown” – markdown 视图
  • “items” – 结构化版面树
  • “metadata” – 页级/任务级元数据(含置信度)

下载这份报告:

终端窗口

curl -fL -o executive-summary-2024.pdf https://fiscal.treasury.gov/system/files/files/reports-statements/financial-report/2024/executive-summary-2024.pdf
  • Python
  • TypeScript
  • Go
  • Java
  • CLI
# 1) Upload the file
file = client.files.create(
    file="executive-summary-2024.pdf",
    purpose="parse",
)

# 2) Parse it, requesting all four inline views
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    expand=["markdown", "text", "metadata", "items"],
)
import fs from 'fs';

// 1) Upload the file
const file = await client.files.create({
  file: fs.createReadStream('executive-summary-2024.pdf'),
  purpose: 'parse',
});

// 2) Parse it, requesting all four inline views
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  expand: ['markdown', 'text', 'metadata', 'items'],
});
// 1) Upload the file
f, err := os.Open("executive-summary-2024.pdf")
if err != nil {
  log.Fatal(err)
}
defer f.Close()

file, err := client.Files.New(ctx, llamacloud.FileNewParams{
  File:    f,
  Purpose: "parse",
})
if err != nil {
  log.Fatal(err)
}

// 2) Create the parse job
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgentic,
  Version: llamacloud.ParsingNewParamsVersionLatest,
})
if err != nil {
  log.Fatal(err)
}

// 3) expand is a GET parameter in Go — poll, then request all four views at once
getParams := llamacloud.ParsingGetParams{Expand: []string{"markdown", "text", "metadata", "items"}}
result, err := client.Parsing.Get(ctx, job.ID, getParams)
if err != nil {
  log.Fatal(err)
}
for result.Job.Status != "COMPLETED" && result.Job.Status != "FAILED" && result.Job.Status != "CANCELLED" {
  time.Sleep(2 * time.Second)
  result, err = client.Parsing.Get(ctx, job.ID, getParams)
  if err != nil {
    log.Fatal(err)
  }
}
if result.Job.Status != "COMPLETED" {
  log.Fatalf("parse ended as %s", result.Job.Status)
}
// 1) Upload the file
FileCreateResponse file = client.files().create(FileCreateParams.builder()
        .file(Paths.get("executive-summary-2024.pdf"))
        .purpose("parse")
        .build());

// 2) Create the parse job
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .build());

// 3) expand is a query parameter in Java — poll, then request all four views at once
ParsingGetParams getParams = ParsingGetParams.builder()
        .jobId(job.id())
        .addExpand("markdown")
        .addExpand("text")
        .addExpand("metadata")
        .addExpand("items")
        .build();

ParsingGetResponse result = client.parsing().get(getParams);
while (!result.job().status().equals(ParsingGetResponse.Job.Status.COMPLETED)
        && !result.job().status().equals(ParsingGetResponse.Job.Status.FAILED)
        && !result.job().status().equals(ParsingGetResponse.Job.Status.CANCELLED)) {
    Thread.sleep(2000);
    result = client.parsing().get(getParams);
}
if (!result.job().status().equals(ParsingGetResponse.Job.Status.COMPLETED)) {
    throw new RuntimeException("parse ended as " + result.job().status());
}

终端窗口

# 1) Upload the file
FILE_ID=$(llp files create \
  --file ./executive-summary-2024.pdf \
  --purpose parse | jq -r '.id')

# 2) Start a parse job
JOB_ID=$(llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest | jq -r '.id')

# 3) Poll until the job reaches a terminal status
while true; do
  STATUS=$(llp parsing get --job-id "$JOB_ID" | jq -er '.job.status') || break
  case "$STATUS" in COMPLETED|FAILED|CANCELLED) break ;; esac
  sleep 2
done

# expand is a query parameter — request all four views at once and save the result
llp parsing get --job-id "$JOB_ID" \
  --expand markdown \
  --expand text \
  --expand metadata \
  --expand items > result.json

jq -e '.job.status == "COMPLETED"' result.json >/dev/null \
  || jq -r '"Parse job failed: \(.job.error_message // .)"' result.json >&2

此时结果里就带着同一份文档的四种视图。在 Go、Java 与 CLI 里,expand 是取结果时的查询参数,所以那几种语言是先创建任务、轮询到结束,再用一次 get 请求这四种视图。

如何选择 expand 输出

你可以一次请求一个或多个 expand 取值。展开项越多,响应越大、延迟也略高,因此生产环境里可以只请求你流水线要用的那几项(例如只来 “text” + “metadata”,或只要 “markdown”)。

3. 理解输出

Text 视图(result.text)

text 视图给出逐页、打平后的干净文本 —— 适合基础检索,或喂给下游的检索环节。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
first_page_text = result.text.pages[0].text
print(first_page_text)
const firstPageText = result.text.pages[0].text;
console.log(firstPageText);
firstPageText := result.Text.Pages[0].Text
fmt.Println(firstPageText)
String firstPageText = result.text().get().pages().get(0).text();
System.out.println(firstPageText);

终端窗口

jq -r '.text.pages[0].text' result.json

你会看到第一页的纯文本:

1                  EXECUTIVE SUMMARY TO THE FY 2024 FINANCIAL REPORT OF THE U.S. GOVERNMENT

                                            NATION BY THE NUMBERS
                                                A Snapshot of
                               The Government's Financial Position & Condition             2023*
                                                                            2024
                                  Financial Measures (Dollars in Billions):
     Net Cost:
      Gross Costs                                                $          (7,772.2) $            (7,661.7)
      Less: Earned Revenue                                                  652.9 $                539.5
      Gain/(Loss) from Changes in Assumptions                    $          (283.6) $                (760.6)
     Total Net Cost                                              $          (7,402.9)              (7,882.8)
                                                                 $          4,977.9 $
     Less: Total Tax and Other Unearned Revenues                                      $     4,465.6
     Net Operating Cost                                          $          (2,425.0) $     (3,417.2)
     Budget Deficit                                              $          (1,832.8) $     (1,695.2)
     Assets, comprised of:                                      20          1,177.7                922.2
      Cash and Other Monetary Assets                                                 $
      Inventory and Related Property, Net                                   447.3 $                423.0
      Loans Receivable, Net                                      1,751.0 $                   1,695.1
      Property, Plant, and Equipment, Net                        1,313.0 $                   1,235.0
      Other                                                                 973.1     $      1,143.8
     Total Assets                                                $            5,662.1 $      5,419.1
     Less: Liabilities, comprised of:                                       (28,338.9) $     (26,347.7)
      Federal Debt and Interest Payable                          $
      Federal Employee and Veteran Benefits Payable             $ (15,033.4)$                     (14,347.6)
      Other                                                      $          (2,173.6)              (2,203.0)
                                                                                     $
     Total Liabilities                                           $ (45,545.9)$                    (42,898.3)
     Net Position                                                $         (39,883.8) $      (37,479.2)
                               Sustainability Measures (Dollars in Trillions):               (78.4)
     Social Insurance Net Expenditures                           $             (78.3) $
     Total Federal Non-Interest Net Expenditures                 $             (72.7) $      (73.2)
                                   Sustainability Measures as Percent GDP:                   (4.4%)
     Social Insurance Net Expenditures2                            (4.2%)
     Total Federal Non-Interest Net Expenditures                   (3.6%)                    (3.8%)
     Fiscal Gap3                                                   (4.3%)                    (4.5%)

      The government's net position is calculated in accordance with federal accounting standards. Per
      these standards, net position does not include the financial value of the government's sovereign power
      to tax, regulate commerce, or set monetary policy, or the value of nonoperational resources, such as
      national and natural resources, for which the government is a steward.
      Pursuant to federal accounting standards, for SOsl reporting, the federal government's social
      insurance programs include Social Security; Medicare Parts A, B, and D; DOL's Black Lung program;
      and the RRB.
      To prevent the debt-to-GDP ratio from rising over the next 75 years, a combination of non-interest
      spending reductions and receipts increases that amount to 4.3 percent of GDP on average is needed
      (4.5 percent of GDP on average in FY 2023). See Financial Statement Note 24.
      Change in presentation (see Financial Statement Note 1.W).

Markdown 视图(result.markdown)

markdown 视图保留标题、列表与表格这类结构。在许多 RAG 流水线里,这是对 LLM 最友好的表示。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
first_page_markdown = result.markdown.pages[0].markdown
print(first_page_markdown)
const firstPageMarkdown = result.markdown.pages[0].markdown;
console.log(firstPageMarkdown);
firstPageMarkdown := result.Markdown.Pages[0].Markdown
fmt.Println(firstPageMarkdown)
String firstPageMarkdown = result.markdown().get().pages().get(0).asMarkdownResult().markdown();
System.out.println(firstPageMarkdown);

终端窗口

jq -r '.markdown.pages[0].markdown' result.json

你会看到与原始文档相近的内容,只是以 markdown 表达(例如 # Headings、项目符号列表与竖线表格)。

# NATION BY THE NUMBERS
## A Snapshot of The Government's Financial Position & Condition

<table>
  <thead>
    <tr>
        <th colspan="3">Financial Measures (Dollars in Billions):</th>
    </tr>
    <tr>
        <th></th>
        <th>2024</th>
        <th>2023*</th>
    </tr>
  </thead>
  <tbody>
    <tr>
        <td>Net Cost:</td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td>Gross Costs</td>
        <td>$ (7,772.2)</td>
        <td>$ (7,661.7)</td>
    </tr>
    <tr>
        <td>Less: Earned Revenue</td>
        <td>$ 652.9</td>
        <td>$ 539.5</td>
    </tr>
    <tr>
        <td>Gain/(Loss) from Changes in Assumptions</td>
        <td>$ (283.6)</td>
        <td>$ (760.6)</td>
    </tr>
    <tr>
        <td>Total Net Cost</td>
        <td>$ (7,402.9)</td>
        <td>$ (7,882.8)</td>
    </tr>
    <tr>
        <td>Less: Total Tax and Other Unearned Revenues</td>
        <td>$ 4,977.9</td>
        <td>$ 4,465.6</td>
    </tr>
    <tr>
        <td>Net Operating Cost</td>
        <td>$ (2,425.0)</td>
        <td>$ (3,417.2)</td>
    </tr>
    <tr>
        <td>Budget Deficit</td>
        <td>$ (1,832.8)</td>
        <td>$ (1,695.2)</td>
    </tr>
    <tr>
        <td>Assets, comprised of:</td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td>Cash and Other Monetary Assets</td>
        <td>$ 1,177.7</td>
        <td>$ 922.2</td>
    </tr>
    <tr>
        <td>Inventory and Related Property, Net</td>
        <td>$ 447.3</td>
        <td>$ 423.0</td>
    </tr>
    <tr>
        <td>Loans Receivable, Net</td>
        <td>$ 1,751.0</td>
        <td>$ 1,695.1</td>
    </tr>
    <tr>
        <td>Property, Plant, and Equipment, Net</td>
        <td>$ 1,313.0</td>
        <td>$ 1,235.0</td>
    </tr>
    <tr>
        <td>Other</td>
        <td>$ 973.1</td>
        <td>$ 1,143.8</td>
    </tr>
    <tr>
        <td>Total Assets</td>
        <td>$ 5,662.1</td>
        <td>$ 5,419.1</td>
    </tr>
    <tr>
        <td>Less: Liabilities, comprised of:</td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td>Federal Debt and Interest Payable</td>
        <td>$ (28,338.9)</td>
        <td>$ (26,347.7)</td>
    </tr>
    <tr>
        <td>Federal Employee and Veteran Benefits Payable</td>
        <td>$ (15,033.4)</td>
        <td>$ (14,347.6)</td>
    </tr>
    <tr>
        <td>Other</td>
        <td>$ (2,173.6)</td>
        <td>$ (2,203.0)</td>
    </tr>
    <tr>
        <td>Total Liabilities</td>
        <td>$ (45,545.9)</td>
        <td>$ (42,898.3)</td>
    </tr>
    <tr>
        <td>Net Position¹</td>
        <td>$ (39,883.8)</td>
        <td>$ (37,479.2)</td>
    </tr>
    <tr>
        <td colspan="3">Sustainability Measures (Dollars in Trillions):</td>
    </tr>
    <tr>
        <td>Social Insurance Net Expenditures</td>
        <td>$ (78.3)</td>
        <td>$ (78.4)</td>
    </tr>
    <tr>
        <td>Total Federal Non-Interest Net Expenditures</td>
        <td>$ (72.7)</td>
        <td>$ (73.2)</td>
    </tr>
    <tr>
        <td colspan="3">Sustainability Measures as Percent GDP:</td>
    </tr>
    <tr>
        <td>Social Insurance Net Expenditures²</td>
        <td>(4.2%)</td>
        <td>(4.4%)</td>
    </tr>
    <tr>
        <td>Total Federal Non-Interest Net Expenditures</td>
        <td>(3.6%)</td>
        <td>(3.8%)</td>
    </tr>
    <tr>
        <td>Fiscal Gap³</td>
        <td>(4.3%)</td>
        <td>(4.5%)</td>
    </tr>
  </tbody>
</table>

> ¹ The government's net position is calculated in accordance with federal accounting standards. Per these standards, net position does not include the financial value of the government's sovereign power to tax, regulate commerce, or set monetary policy, or the value of nonoperational resources, such as national and natural resources, for which the government is a steward.
>
> ² Pursuant to federal accounting standards, for SOSI reporting, the federal government's social insurance programs include Social Security; Medicare Parts A, B, and D; DOL's Black Lung program; and the RRB.
>
> ³ To prevent the debt-to-GDP ratio from rising over the next 75 years, a combination of non-interest spending reductions and receipts increases that amount to 4.3 percent of GDP on average is needed (4.5 percent of GDP on average in FY 2023). See Financial Statement Note 24.
>
> \* Change in presentation (see Financial Statement Note 1.W).

Items 视图(result.items)

items 视图是每页元素的结构化树:段落、表格、图形等。需要细粒度的、感知版面的处理时用它。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
first_page_items = result.items.pages[0].items

for item in first_page_items[:5]:
    print(item.type, item)
const firstPageItems = result.items.pages[0].items;

for (const item of firstPageItems.slice(0, 5)) {
  console.log(item.type, item);
}
firstPageItems := result.Items.Pages[0].Items

for i, item := range firstPageItems {
  if i >= 5 {
    break
  }
  fmt.Printf("%s: %s\n", item.Type, item.Md)
}
ParsingGetResponse.Items.Page.StructuredResultPage firstPage =
        result.items().get().pages().get(0).asStructuredResult();

for (ParsingGetResponse.Items.Page.StructuredResultPage.Item item : firstPage.items()) {
    if (item.isHeader()) {
        System.out.println("header: " + item.asHeader().md());
    } else if (item.isHeading()) {
        System.out.println("heading: " + item.asHeading().md());
    } else if (item.isTable()) {
        System.out.println("table: " + item.asTable().rows().size() + " rows");
    } else if (item.isText()) {
        System.out.println("text: " + item.asText().md());
    } else if (item.isImage()) {
        System.out.println("image: " + item.asImage().md());
    }
}

终端窗口

jq -r '.items.pages[0].items[0:5][] | .type' result.json

常见的 type 取值有 header、heading、text、table 与 image。表格带着行数据;图片可以指向图形或图表。

// Each item carries a `type`, a markdown `md` string, and layout `bbox`es.
// Table items also include `rows`, `csv`, and `html`; image items reference figures or charts.
[
  { "type": "header",  "md": "1 EXECUTIVE SUMMARY TO THE FY 2024 FINANCIAL REPORT OF THE U.S. GOVERNMENT" },
  { "type": "heading", "level": 1, "md": "# NATION BY THE NUMBERS" },
  { "type": "heading", "level": 2, "md": "## A Snapshot of The Government's Financial Position & Condition" },
  { "type": "table",   "rows": [["Financial Measures (Dollars in Billions):", "2024", "2023*"], ["Gross Costs", "$ (7,772.2)", "$ (7,661.7)"]] },
  { "type": "text",    "md": "¹ The government's net position is calculated in accordance with federal accounting standards..." }
]

Metadata 视图(result.metadata)

metadata 视图暴露页级与任务级元数据,例如置信度得分,以及演示文稿专有的数据。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
first_page_meta = result.metadata.pages[0]

print("Page number:", first_page_meta.page_number)
print("Confidence:", first_page_meta.confidence)
const firstPageMeta = result.metadata.pages[0];

console.log("Page number:", firstPageMeta.page_number);
console.log("Confidence:", firstPageMeta.confidence);
firstPageMeta := result.Metadata.Pages[0]

fmt.Println("Page number:", firstPageMeta.PageNumber)
fmt.Println("Confidence:", firstPageMeta.Confidence)
ParsingGetResponse.Metadata.Page firstPageMeta = result.metadata().get().pages().get(0);

System.out.println("Page number: " + firstPageMeta.pageNumber());
System.out.println("Confidence: " + firstPageMeta.confidence().orElse(null));

终端窗口

jq -r '.metadata.pages[0] | "Page number: \(.page_number)\nConfidence: \(.confidence)"' result.json
  • page_number 指明这段元数据对应哪一页。
  • confidence 是解析器对该页的相对置信得分(0–1)。
  • 其他字段(例如演示文稿的 slide speaker_notes)视输入类型而定。
Page number: 1
Confidence: 0.985

完整的逐页元数据对象在各语言里字段一致 —— 页号、置信度,以及演示文稿专有的那些标记:

{
  "page_number": 1,
  "confidence": 0.985,
  "cost_optimized": false,
  "original_orientation_angle": 0,
  "printed_page_number": null,
  "slide_section_name": null,
  "speaker_notes": null,
  "triggered_auto_mode": false
}

这四种视图合起来能让你:

  • 把 text 或 markdown 直接用于 LLM 流水线。
  • 需要表格、图形或显式版面时用 items。
  • 用 metadata 做质量检查、把低置信页转人工,或做分析。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。