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

**给 Parse 用户最常遇到的模式准备的、可直接复制粘贴的小片段。**每条配方约 ~10-20 行,回答一个具体的“我该怎么做 X?”问题。拿去放进你的项目、按需改动即可。

完整的走查见 Parse 示例 教程。完整的 API 参考见 REST API 指南。

把 API key 设一次,让各 SDK 与 CLI 自动读取:

终端窗口

export LLAMA_CLOUD_API_KEY="llx-..."

先下载一份样例 PDF —— 财政服务局的 FY2024 执行摘要,存为 doc.pdf:

终端窗口

curl -fL -o doc.pdf https://fiscal.treasury.gov/system/files/files/reports-statements/financial-report/2024/executive-summary-2024.pdf

下面每条配方都假定你已经构造好一个 client 并上传了一个 file:

  • 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
file = client.files.create(file="doc.pdf", purpose="parse")

终端窗口

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

const client = new LlamaCloud(); // reads LLAMA_CLOUD_API_KEY from the environment
const file = await client.files.create({
  file: fs.createReadStream('doc.pdf'),
  purpose: 'parse',
});

终端窗口

go get github.com/run-llama/llama-parse-go
package main

import (
  "context"
  "log"
  "os"

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

func main() {
  ctx := context.Background()
  client := llamacloud.NewClient() // reads LLAMA_CLOUD_API_KEY from the environment

  f, err := os.Open("doc.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)
  }

  // ... a recipe goes here, using ctx, client, and file ...
  _ = file
}
implementation("ai.llamaindex:llama-cloud:1.3.0")
import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
import ai.llamaindex.llamacloud.core.JsonValue;
import ai.llamaindex.llamacloud.models.files.FileCreateParams;
import ai.llamaindex.llamacloud.models.files.FileCreateResponse;
import ai.llamaindex.llamacloud.models.parsing.ParsingCreateParams;
import ai.llamaindex.llamacloud.models.parsing.ParsingCreateResponse;
import ai.llamaindex.llamacloud.models.parsing.ParsingGetParams;
import ai.llamaindex.llamacloud.models.parsing.ParsingGetResponse;
import ai.llamaindex.llamacloud.models.parsing.ParsingLanguages;
import java.nio.file.Paths;

LlamaCloudClient client = LlamaCloudOkHttpClient.fromEnv();
FileCreateResponse file = client.files().create(FileCreateParams.builder()
        .file(Paths.get("doc.pdf"))
        .purpose("parse")
        .build());

终端窗口

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

终端窗口

# llp reads LLAMA_CLOUD_API_KEY from the environment
FILE_ID=$(llp files create --file doc.pdf --purpose parse | jq -r '.id')

expand 该放在哪儿

Python 与 TypeScript 把 expand 直接传给阻塞式的 parse() 调用。而在 Go、Java 与 CLI 里,expand 是结果端点上的参数,所以那三种要先创建任务、轮询到终态,再带着想要的字段取结果。下面每条配方都遵循这一划分。

端到端解析一个文档

最小可用:上传文件、解析、把 markdown 打出来。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    expand=["markdown"],
)
print(result.markdown.pages[0].markdown)
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  expand: ['markdown'],
});
console.log(result.markdown.pages[0].markdown);
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)
}

// expand is a GET parameter in Go — request markdown when you poll for the result
getParams := llamacloud.ParsingGetParams{Expand: []string{"markdown"}}
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)
}

fmt.Println(result.Markdown.Pages[0].Markdown)
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .build());

// expand is a query parameter in Java — request markdown when you poll for the result
ParsingGetParams getParams = ParsingGetParams.builder()
        .jobId(job.id())
        .addExpand("markdown")
        .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());
}

System.out.println(result.markdown().get().pages().get(0).asMarkdownResult().markdown());

终端窗口

JOB_ID=$(llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest | jq -r '.id')

# 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

# Print the markdown for the first page
llp parsing get --job-id "$JOB_ID" --expand markdown \
  | jq -r 'if .job.status == "COMPLETED" then .markdown.pages[0].markdown
    else "Parse job failed: \(.job.error_message // .)" end'

为生产环境固定版本

用带日期的 version,这样模型更新就不会在你不知情时改变你的输出。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="2026-04-06",  # pin a specific date
    expand=["markdown"],
)
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: '2026-04-06', // pin a specific date
  expand: ['markdown'],
});
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgentic,
  Version: llamacloud.ParsingNewParamsVersion("2026-04-06"), // pin a specific date
})
if err != nil {
  log.Fatal(err)
}
// poll job.ID until COMPLETED, then fetch with expand (see "Parse a document end-to-end")
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version("2026-04-06") // pin a specific date
        .build());
// poll job.id() until COMPLETED, then fetch with expand (see "Parse a document end-to-end")

终端窗口

llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version 2026-04-06   # pin a specific date

可用的最新日期见档位 → 版本化与可复现。

只解析指定的页

跳过无关的页,把 credit 省下来。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    page_ranges={"target_pages": "1,3,5-10"},  # 1-indexed
    expand=["markdown"],
)
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  page_ranges: { target_pages: '1,3,5-10' }, // 1-indexed
  expand: ['markdown'],
});
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgentic,
  Version: llamacloud.ParsingNewParamsVersionLatest,
  PageRanges: llamacloud.ParsingNewParamsPageRanges{
    TargetPages: llamacloud.String("1,3,5-10"), // 1-indexed
  },
})
if err != nil {
  log.Fatal(err)
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .pageRanges(ParsingCreateParams.PageRanges.builder()
                .targetPages("1,3,5-10") // 1-indexed
                .build())
        .build());

终端窗口

llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest \
  --page-ranges.target-pages '1,3,5-10'   # 1-indexed

你也可以用 max_pages(CLI 上是 --page-ranges.max-pages)给总量设上限。

从每一页裁掉页眉页脚

解析前从每一页的顶部与底部各裁掉一段固定边距。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    crop_box={"top": 0.08, "bottom": 0.08, "left": 0, "right": 0},
    expand=["markdown"],
)
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  crop_box: { top: 0.08, bottom: 0.08, left: 0, right: 0 },
  expand: ['markdown'],
});
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgentic,
  Version: llamacloud.ParsingNewParamsVersionLatest,
  CropBox: llamacloud.ParsingNewParamsCropBox{
    Top:    llamacloud.Float(0.08),
    Bottom: llamacloud.Float(0.08),
  },
})
if err != nil {
  log.Fatal(err)
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .cropBox(ParsingCreateParams.CropBox.builder()
                .top(0.08)
                .bottom(0.08)
                .build())
        .build());

终端窗口

llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest \
  --crop-box.top 0.08 \
  --crop-box.bottom 0.08

取值是页高/页宽的比例(0.0–1.0)。

多语言 OCR

为非英语文档给 OCR 引擎提示语言。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    processing_options={
        "ocr_parameters": {"languages": ["en", "fr", "de"]},
    },
    expand=["markdown"],
)
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  processing_options: {
    ocr_parameters: { languages: ['en', 'fr', 'de'] },
  },
  expand: ['markdown'],
});
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgentic,
  Version: llamacloud.ParsingNewParamsVersionLatest,
  ProcessingOptions: llamacloud.ParsingNewParamsProcessingOptions{
    OcrParameters: llamacloud.ParsingNewParamsProcessingOptionsOcrParameters{
      Languages: []llamacloud.ParsingLanguages{
        llamacloud.ParsingLanguagesEn,
        llamacloud.ParsingLanguagesFr,
        llamacloud.ParsingLanguagesDe,
      },
    },
  },
})
if err != nil {
  log.Fatal(err)
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .processingOptions(ParsingCreateParams.ProcessingOptions.builder()
                .ocrParameters(ParsingCreateParams.ProcessingOptions.OcrParameters.builder()
                        .addLanguage(ParsingLanguages.EN)
                        .addLanguage(ParsingLanguages.FR)
                        .addLanguage(ParsingLanguages.DE)
                        .build())
                .build())
        .build());

终端窗口

llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest \
  --processing-options.ocr-parameters '{languages: [en, fr, de]}'

在长短不一、复杂度混合的文档上省钱

开启成本优化器,让简单页自动路由到 cost_effective,然后读逐页元数据看哪些页拿到了更便宜的档位。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic_plus",
    version="latest",
    processing_options={
        "cost_optimizer": {"enable": True},
    },
    expand=["markdown", "metadata"],
)

# See which pages got the cheaper tier
for page in result.metadata.pages:
    flag = "cost-optimized" if page.cost_optimized else "premium"
    print(f"page {page.page_number}: {flag}")
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic_plus',
  version: 'latest',
  processing_options: {
    cost_optimizer: { enable: true },
  },
  expand: ['markdown', 'metadata'],
});

// See which pages got the cheaper tier
for (const page of result.metadata.pages) {
  const flag = page.cost_optimized ? 'cost-optimized' : 'premium';
  console.log(`page ${page.page_number}: ${flag}`);
}
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgenticPlus,
  Version: llamacloud.ParsingNewParamsVersionLatest,
  ProcessingOptions: llamacloud.ParsingNewParamsProcessingOptions{
    CostOptimizer: llamacloud.ParsingNewParamsProcessingOptionsCostOptimizer{
      Enable: llamacloud.Bool(true),
    },
  },
})
if err != nil {
  log.Fatal(err)
}

getParams := llamacloud.ParsingGetParams{Expand: []string{"markdown", "metadata"}}
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)
}

// See which pages got the cheaper tier
for _, page := range result.Metadata.Pages {
  flag := "premium"
  if page.CostOptimized {
    flag = "cost-optimized"
  }
  fmt.Printf("page %d: %s\n", page.PageNumber, flag)
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC_PLUS)
        .version(ParsingCreateParams.Version.LATEST)
        .processingOptions(ParsingCreateParams.ProcessingOptions.builder()
                .costOptimizer(ParsingCreateParams.ProcessingOptions.CostOptimizer.builder()
                        .enable(true)
                        .build())
                .build())
        .build());

ParsingGetParams getParams = ParsingGetParams.builder()
        .jobId(job.id())
        .addExpand("markdown")
        .addExpand("metadata")
        .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());
}

// See which pages got the cheaper tier
for (ParsingGetResponse.Metadata.Page page : result.metadata().get().pages()) {
    String flag = page.costOptimized().orElse(false) ? "cost-optimized" : "premium";
    System.out.printf("page %d: %s%n", page.pageNumber(), flag);
}

终端窗口

JOB_ID=$(llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic_plus \
  --version latest \
  --processing-options.cost-optimizer '{enable: true}' | jq -r '.id')

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

# See which pages got the cheaper tier
llp parsing get --job-id "$JOB_ID" --expand metadata \
  | jq -r 'if .job.status == "COMPLETED" then .metadata.pages[] | "page \(.page_number): \(if .cost_optimized then "cost-optimized" else "premium" end)"
    else "Parse job failed: \(.job.error_message // .)" end'

见成本优化器。

用自定义提示词引导解析器

告诉智能体式模型该把注意力放在哪里。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    agentic_options={
        "custom_prompt": "This is a financial 10-K. Preserve currency symbols on every number and keep the original section hierarchy.",
    },
    expand=["markdown"],
)
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  agentic_options: {
    custom_prompt:
      'This is a financial 10-K. Preserve currency symbols on every number and keep the original section hierarchy.',
  },
  expand: ['markdown'],
});
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgentic,
  Version: llamacloud.ParsingNewParamsVersionLatest,
  AgenticOptions: llamacloud.ParsingNewParamsAgenticOptions{
    CustomPrompt: llamacloud.String("This is a financial 10-K. Preserve currency symbols on every number and keep the original section hierarchy."),
  },
})
if err != nil {
  log.Fatal(err)
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .agenticOptions(ParsingCreateParams.AgenticOptions.builder()
                .customPrompt("This is a financial 10-K. Preserve currency symbols on every number and keep the original section hierarchy.")
                .build())
        .build());

终端窗口

llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest \
  --agentic-options.custom-prompt 'This is a financial 10-K. Preserve currency symbols on every number and keep the original section hierarchy.'

提示词写法技巧见自定义提示词。

把表格抽进 pandas

取结构化 items、遍历找表格、载入 DataFrame。表格到 DataFrame 这一步是 Python + pandas —— 至于如何在 TypeScript、Go、Java 或 CLI 里取 items 树,见取回结果 → markdown 加结构化 items 树。

import io
import pandas as pd

result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    expand=["items"],
)

# Find the first table on page 3 and load it
page = result.items.pages[2]  # 0-indexed in the items tree
table = next(item for item in page.items if getattr(item, "type", None) == "table")

df = pd.read_csv(io.StringIO(table.csv))
print(df.head())

带图表的端到端版本见解析 PDF 中的图表并用 pandas 分析 教程。

为多模态流水线取逐页截图

保存整页截图,并在一块 markdown 旁列出它们的预签名下载地址,一起交给 LLM。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    output_options={"images_to_save": ["screenshot"]},
    expand=["markdown_full", "images_content_metadata"],
)

# One big markdown blob for the LLM
markdown_blob = result.markdown_full

# Each page screenshot as a downloadable URL
for image in result.images_content_metadata.images:
    print(f"{image.filename}: {image.presigned_url}")
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  output_options: { images_to_save: ['screenshot'] },
  expand: ['markdown_full', 'images_content_metadata'],
});

// One big markdown blob for the LLM
const markdownBlob = result.markdown_full;

// Each page screenshot as a downloadable URL
for (const image of result.images_content_metadata?.images ?? []) {
  console.log(`${image.filename}: ${image.presigned_url}`);
}
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgentic,
  Version: llamacloud.ParsingNewParamsVersionLatest,
  OutputOptions: llamacloud.ParsingNewParamsOutputOptions{
    ImagesToSave: []string{"screenshot"},
  },
})
if err != nil {
  log.Fatal(err)
}

getParams := llamacloud.ParsingGetParams{Expand: []string{"markdown_full", "images_content_metadata"}}
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)
}

// One big markdown blob for the LLM
markdownBlob := result.MarkdownFull
_ = markdownBlob

// Each page screenshot as a downloadable URL
for _, image := range result.ImagesContentMetadata.Images {
  fmt.Printf("%s: %s\n", image.Filename, image.PresignedURL)
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .outputOptions(ParsingCreateParams.OutputOptions.builder()
                .addImagesToSave(ParsingCreateParams.OutputOptions.ImagesToSave.SCREENSHOT)
                .build())
        .build());

ParsingGetParams getParams = ParsingGetParams.builder()
        .jobId(job.id())
        .addExpand("markdown_full")
        .addExpand("images_content_metadata")
        .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());
}

// One big markdown blob for the LLM
String markdownBlob = result.markdownFull().orElse("");

// Each page screenshot as a downloadable URL
for (ParsingGetResponse.ImagesContentMetadata.Image image : result.imagesContentMetadata().get().images()) {
    System.out.println(image.filename() + ": " + image.presignedUrl().orElse(""));
}

终端窗口

JOB_ID=$(llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest \
  --output-options.images-to-save '[screenshot]' | jq -r '.id')

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

# markdown blob + each page screenshot as a downloadable URL
llp parsing get --job-id "$JOB_ID" \
  --expand markdown_full \
  --expand images_content_metadata \
  | jq -r 'if .job.status == "COMPLETED" then .images_content_metadata.images[] | "\(.filename): \(.presigned_url)"
    else "Parse job failed: \(.job.error_message // .)" end'

每个 presigned_url 只需一次普通 HTTP GET 就能拿到图片字节。在 Python 里:

import requests

for image in result.images_content_metadata.images:
    img_bytes = requests.get(image.presigned_url).content
    with open(image.filename, "wb") as f:
        f.write(img_bytes)

用 webhook 推送结果而不是轮询

对长时间运行的任务,让 Parse 在任务结束时回调你。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic_plus",
    version="latest",
    webhook_configurations=[
        {
            "webhook_url": "https://your-app.com/parse-callback",
            "webhook_headers": {"X-My-Auth": "secret"},
        }
    ],
    expand=["markdown"],
)
print(f"Job started: {result.job.id}")
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic_plus',
  version: 'latest',
  webhook_configurations: [
    {
      webhook_url: 'https://your-app.com/parse-callback',
      webhook_headers: { 'X-My-Auth': 'secret' },
    },
  ],
  expand: ['markdown'],
});
console.log(`Job started: ${result.job.id}`);
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:  llamacloud.String(file.ID),
  Tier:    llamacloud.ParsingNewParamsTierAgenticPlus,
  Version: llamacloud.ParsingNewParamsVersionLatest,
  WebhookConfigurations: []llamacloud.ParsingNewParamsWebhookConfiguration{
    {
      WebhookURL:     llamacloud.String("https://your-app.com/parse-callback"),
      WebhookHeaders: map[string]any{"X-My-Auth": "secret"},
    },
  },
})
if err != nil {
  log.Fatal(err)
}
fmt.Printf("Job started: %s\n", job.ID)
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC_PLUS)
        .version(ParsingCreateParams.Version.LATEST)
        .addWebhookConfiguration(ParsingCreateParams.WebhookConfiguration.builder()
                .webhookUrl("https://your-app.com/parse-callback")
                .webhookHeaders(ParsingCreateParams.WebhookConfiguration.WebhookHeaders.builder()
                        .putAdditionalProperty("X-My-Auth", JsonValue.from("secret"))
                        .build())
                .build())
        .build());
System.out.println("Job started: " + job.id());

终端窗口

llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic_plus \
  --version latest \
  --webhook-configuration.webhook-url 'https://your-app.com/parse-callback' \
  --webhook-configuration.webhook-headers '{X-My-Auth: secret}' \
  | jq -r '"Job started: \(.id)"'

任务结束时,Parse 会向你的 URL POST 一条事件通知。见 webhook 配置。

事后再取结果(不重新解析)

任务只跑一次,之后按 job_id 补取更多字段。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
# Step 1 — parse with a minimal expand
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    expand=["markdown"],
)
job_id = result.job.id

# Step 2 — later, in another script, get the items tree for the same job
items_result = client.parsing.get(job_id=job_id, expand=["items"])
for page in items_result.items.pages:
    print(f"page {page.page_number}: {len(page.items)} items")
// Step 1 — parse with a minimal expand
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  expand: ['markdown'],
});
const jobId = result.job.id;

// Step 2 — later, in another script, get the items tree for the same job
const itemsResult = await client.parsing.get(jobId, { expand: ['items'] });
for (const page of itemsResult.items.pages) {
  console.log(`page ${page.page_number}: ${page.items.length} items`);
}
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)
}

// Step 1 — poll until the job reaches a terminal status
getParams := llamacloud.ParsingGetParams{Expand: []string{"markdown"}}
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)
}

// Step 2 — later, get the items tree for the same job
itemsResult, err := client.Parsing.Get(ctx, job.ID, llamacloud.ParsingGetParams{
  Expand: []string{"items"},
})
if err != nil {
  log.Fatal(err)
}
for _, page := range itemsResult.Items.Pages {
  fmt.Printf("page %d: %d items\n", page.PageNumber, len(page.Items))
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version(ParsingCreateParams.Version.LATEST)
        .build());

// Step 1 — poll until the job reaches a terminal status
ParsingGetParams getParams = ParsingGetParams.builder()
        .jobId(job.id())
        .addExpand("markdown")
        .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());
}

// Step 2 — later, get the items tree for the same job
ParsingGetResponse itemsResult = client.parsing().get(ParsingGetParams.builder()
        .jobId(job.id())
        .addExpand("items")
        .build());
for (ParsingGetResponse.Items.Page page : itemsResult.items().get().pages()) {
    if (!page.isStructuredResult()) {
        continue; // skip failed pages
    }
    ParsingGetResponse.Items.Page.StructuredResultPage structured = page.asStructuredResult();
    System.out.printf("page %d: %d items%n", structured.pageNumber(), structured.items().size());
}

终端窗口

# Step 1 — parse and poll until terminal
JOB_ID=$(llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version latest | jq -r '.id')

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

# Step 2 — later, get the items tree for the same job
llp parsing get --job-id "$JOB_ID" --expand items \
  | jq -r 'if .job.status == "COMPLETED" then .items.pages[] | "page \(.page_number): \(.items | length) items"
    else "Parse job failed: \(.job.error_message // .)" end'

所有合法的 expand 取值见取回结果。

任务失败时降到更小的档位重试

如果一个解析任务在 agentic_plus 上失败了(例如遇到不寻常的版式),就退到 agentic 重试,再退到 cost_effective。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
def parse_with_fallback(file_id):
    for tier in ["agentic_plus", "agentic", "cost_effective"]:
        try:
            return client.parsing.parse(
                file_id=file_id,
                tier=tier,
                version="latest",
                expand=["markdown"],
            )
        except Exception as e:
            print(f"tier {tier} failed: {e}")
    raise RuntimeError("all tiers failed")

result = parse_with_fallback(file.id)
async function parseWithFallback(fileId: string) {
  for (const tier of ['agentic_plus', 'agentic', 'cost_effective'] as const) {
    try {
      return await client.parsing.parse({
        file_id: fileId,
        tier,
        version: 'latest',
        expand: ['markdown'],
      });
    } catch (e) {
      console.log(`tier ${tier} failed: ${e}`);
    }
  }
  throw new Error('all tiers failed');
}

const result = await parseWithFallback(file.id);
// In Go a failed job surfaces as a terminal FAILED/CANCELLED status, not an error,
// so the fallback checks the status after polling each tier.
func parseWithFallback(ctx context.Context, client llamacloud.Client, fileID string) (*llamacloud.ParsingGetResponse, error) {
  tiers := []llamacloud.ParsingNewParamsTier{
    llamacloud.ParsingNewParamsTierAgenticPlus,
    llamacloud.ParsingNewParamsTierAgentic,
    llamacloud.ParsingNewParamsTierCostEffective,
  }
  for _, tier := range tiers {
    job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
      FileID:  llamacloud.String(fileID),
      Tier:    tier,
      Version: llamacloud.ParsingNewParamsVersionLatest,
    })
    if err != nil {
      fmt.Printf("tier %s failed: %v\n", tier, err)
      continue
    }

    getParams := llamacloud.ParsingGetParams{Expand: []string{"markdown"}}
    result, err := client.Parsing.Get(ctx, job.ID, getParams)
    if err != nil {
      fmt.Printf("tier %s failed: %v\n", tier, err)
      continue
    }
    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 {
        return nil, err
      }
    }
    if result.Job.Status == "COMPLETED" {
      return result, nil
    }
    fmt.Printf("tier %s ended as %s\n", tier, result.Job.Status)
  }
  return nil, fmt.Errorf("all tiers failed")
}
// In Java a failed job surfaces as a terminal FAILED/CANCELLED status, not an exception,
// so the fallback checks the status after polling each tier.
ParsingGetResponse result = null;
for (ParsingCreateParams.Tier tier : new ParsingCreateParams.Tier[]{
        ParsingCreateParams.Tier.AGENTIC_PLUS,
        ParsingCreateParams.Tier.AGENTIC,
        ParsingCreateParams.Tier.COST_EFFECTIVE}) {
    ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
            .fileId(file.id())
            .tier(tier)
            .version(ParsingCreateParams.Version.LATEST)
            .build());

    ParsingGetParams getParams = ParsingGetParams.builder()
            .jobId(job.id())
            .addExpand("markdown")
            .build();

    ParsingGetResponse candidate = client.parsing().get(getParams);
    while (!candidate.job().status().equals(ParsingGetResponse.Job.Status.COMPLETED)
            && !candidate.job().status().equals(ParsingGetResponse.Job.Status.FAILED)
            && !candidate.job().status().equals(ParsingGetResponse.Job.Status.CANCELLED)) {
        Thread.sleep(2000);
        candidate = client.parsing().get(getParams);
    }
    if (candidate.job().status().equals(ParsingGetResponse.Job.Status.COMPLETED)) {
        result = candidate;
        break;
    }
    System.out.printf("tier %s ended as %s%n", tier, candidate.job().status());
}
if (result == null) {
    throw new RuntimeException("all tiers failed");
}

终端窗口

for TIER in agentic_plus agentic cost_effective; do
  JOB_ID=$(llp parsing create \
    --file-id "$FILE_ID" \
    --tier "$TIER" \
    --version latest | jq -r '.id')

  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

  if [ "$STATUS" = "COMPLETED" ]; then
    echo "parsed on tier $TIER"
    break
  fi
  llp parsing get --job-id "$JOB_ID" \
    | jq -r --arg tier "$TIER" '"tier \($tier) failed: \(.job.error_message // .)"'
done

关掉缓存以强制重新解析

当你需要一次确定的重新解析时(例如换了档位版本之后),跳过缓存结果。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="2026-04-06",
    disable_cache=True,
    expand=["markdown"],
)
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: '2026-04-06',
  disable_cache: true,
  expand: ['markdown'],
});
job, err := client.Parsing.New(ctx, llamacloud.ParsingNewParams{
  FileID:       llamacloud.String(file.ID),
  Tier:         llamacloud.ParsingNewParamsTierAgentic,
  Version:      llamacloud.ParsingNewParamsVersion("2026-04-06"),
  DisableCache: llamacloud.Bool(true),
})
if err != nil {
  log.Fatal(err)
}
ParsingCreateResponse job = client.parsing().create(ParsingCreateParams.builder()
        .fileId(file.id())
        .tier(ParsingCreateParams.Tier.AGENTIC)
        .version("2026-04-06")
        .disableCache(true)
        .build());

终端窗口

llp parsing create \
  --file-id "$FILE_ID" \
  --tier agentic \
  --version 2026-04-06 \
  --disable-cache=true

见缓存控制。

另请参阅

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