Skip to content
LlamaParse 文档版本 跟随上游 源快照 5f0bd5ac 更新于 2026-10-17

构建由智能体式 OCR 驱动的文档智能体。

LlamaParse 是 LlamaIndex 面向企业的文档转生产 AI 流水线平台。一个 API key、一个 SDK,五个可组合的产品:Parse(智能体式 OCR)、Extract(结构化数据)、Classify、Split 与 Index。

在用编码智能体?

给你的 AI 智能体开放这些文档的访问:claude mcp add llama-index-docs --transport http https://developers.llamaindex.ai/mcp —— 或者用 LlamaParse 的 MCP 工具与技能 给它加强能力。

安装

  • Python
  • TypeScript
  • Go
  • Java
  • CLI

终端窗口

pip install "llama-cloud>=2.8"

终端窗口

npm install @llamaindex/llama-cloud zod

终端窗口

go mod init quickstart  # skip if the directory already has a go.mod
go get github.com/run-llama/llama-parse-go
implementation("ai.llamaindex:llama-cloud:1.3.0")

终端窗口

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

设置你的 API key:

终端窗口

export LLAMA_CLOUD_API_KEY=llx-...

取一把 API key 可在 LlamaParse 控制台 获取。


我该用哪个产品?

把你要做的事对应到合适的产品:

我想做的…用
把 PDF、扫描件或图片变成干净的、可供 LLM 使用的文本Parse
按我的 schema 从文档里抽出结构化 JSONExtract
用自然语言规则把文档分流到各类别Classify
把拼接在一起的文档拆成逻辑上的各份Split
搭建托管的向量检索流水线以支撑 RAGIndex
第一次接触?从 Parse 开始 —— 它是多数流水线的基础。或者往下滑,下面每个产品都给了一段可直接运行的片段。

快速开始

  • Parse
  • Extract
  • Classify
  • Split
  • Index

面向 130 多种格式的智能体式 OCR 与解析。把 PDF 与扫描件变成可供 LLM 使用的文本 —— 这是文档智能体的地基。

下载美国财政部 FY2024 财务报告的执行摘要,存为 document.pdf:

终端窗口

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

Python(python)

复制为智能体上下文

from llama_cloud import LlamaCloud

client = LlamaCloud()  # Uses LLAMA_CLOUD_API_KEY env var

# Upload and parse a document
file = client.files.create(file="document.pdf", purpose="parse")
result = client.parsing.parse(
    file_id=file.id,
    tier="agentic",
    version="latest",
    expand=["markdown"],
)

# Get markdown output
print(result.markdown.pages[0].markdown)

复制为智能体上下文

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

const client = new LlamaCloud(); // Uses LLAMA_CLOUD_API_KEY env var

// Upload and parse a document
const file = await client.files.create({
  file: fs.createReadStream('document.pdf'),
  purpose: 'parse',
});
const result = await client.parsing.parse({
  file_id: file.id,
  tier: 'agentic',
  version: 'latest',
  expand: ['markdown']
});

// Get markdown output
console.log(result.markdown.pages[0].markdown);

复制为智能体上下文

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "time"

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

func main() {
  ctx := context.Background()
  client := llamacloud.NewClient() // Uses LLAMA_CLOUD_API_KEY env var

  // Upload and parse a document
  f, err := os.Open("document.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)
  }

  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)
  }

  // Poll until the job reaches a terminal state
  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 == "PENDING" || result.Job.Status == "RUNNING" {
    time.Sleep(2 * time.Second)
    result, err = client.Parsing.Get(ctx, job.ID, getParams)
    if err != nil {
      log.Fatal(err)
    }
  }

  // Get markdown output
  fmt.Println(result.Markdown.Pages[0].Markdown)
}

复制为智能体上下文

import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
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 java.nio.file.Paths;

public class ParseQuickStart {
    public static void main(String[] args) throws Exception {
        LlamaCloudClient client = LlamaCloudOkHttpClient.fromEnv(); // Uses LLAMA_CLOUD_API_KEY env var

        // Upload and parse a document
        FileCreateResponse file = client.files().create(FileCreateParams.builder()
                .file(Paths.get("document.pdf"))
                .purpose("parse")
                .build());

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

        // Poll until the job reaches a terminal state
        ParsingGetParams getParams = ParsingGetParams.builder()
                .jobId(job.id())
                .addExpand("markdown")
                .build();
        ParsingGetResponse result = client.parsing().get(getParams);
        while (result.job().status().equals(ParsingGetResponse.Job.Status.PENDING)
                || result.job().status().equals(ParsingGetResponse.Job.Status.RUNNING)) {
            Thread.sleep(2000);
            result = client.parsing().get(getParams);
        }

        // Get markdown output
        System.out.println(result.markdown().get().pages().get(0).asMarkdownResult().markdown());
    }
}

复制为智能体上下文

终端窗口

# Upload and parse a document
FILE_ID=$(llp files create --file document.pdf --purpose parse | jq -r '.id')
JOB_ID=$(llp parsing create --file-id "$FILE_ID" --tier agentic --version latest | jq -r '.id')

# Poll until the job reaches a terminal state
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

# Get markdown output
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'

完整指南 | 示例 | 档位与定价

用自定义 schema 从文档里取出结构化数据。为智能体提供干净的实体、表格与字段。

下载一份样例简历,存为 resume.pdf:

终端窗口

curl -fL -o resume.pdf https://raw.githubusercontent.com/run-llama/llama_cloud_services/main/examples/extract/data/resumes/software_architect.pdf

Python(python)

复制为智能体上下文

from pydantic import BaseModel, Field
from llama_cloud import LlamaCloud

# Define your schema
class Resume(BaseModel):
    name: str = Field(description="Full name of candidate")
    email: str = Field(description="Email address")
    skills: list[str] = Field(description="Technical skills")

client = LlamaCloud()

# Upload and extract
file = client.files.create(file="resume.pdf", purpose="extract")
job = client.extract.run(
    file_input=file.id,
    configuration={
        "data_schema": Resume.model_json_schema(),
        "tier": "agentic",
    },
)
print(job.extract_result)

复制为智能体上下文

import LlamaCloud from '@llamaindex/llama-cloud';
import { z } from 'zod';
import fs from 'fs';

// Define your schema with Zod
const ResumeSchema = z.object({
  name: z.string().describe('Full name of candidate'),
  email: z.string().describe('Email address'),
  skills: z.array(z.string()).describe('Technical skills'),
});

const client = new LlamaCloud();

// Upload and extract
const file = await client.files.create({
  file: fs.createReadStream('resume.pdf'),
  purpose: 'extract',
});
let job = await client.extract.run({
  file_input: file.id,
  configuration: {
    data_schema: z.toJSONSchema(ResumeSchema),
    tier: 'agentic',
  },
});
console.log(job.extract_result);

复制为智能体上下文

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "time"

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

func main() {
  ctx := context.Background()
  client := llamacloud.NewClient()

  // Define your schema
  dataSchema := map[string]*llamacloud.ExtractConfigurationDataSchemaUnionParam{
    "type": {OfString: llamacloud.String("object")},
    "properties": {OfAnyMap: map[string]any{
      "name":  map[string]any{"type": "string", "description": "Full name of candidate"},
      "email": map[string]any{"type": "string", "description": "Email address"},
      "skills": map[string]any{
        "type":        "array",
        "items":       map[string]any{"type": "string"},
        "description": "Technical skills",
      },
    }},
  }

  // Upload and extract
  f, err := os.Open("resume.pdf")
  if err != nil {
    log.Fatal(err)
  }
  defer f.Close()

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

  job, err := client.Extract.New(ctx, llamacloud.ExtractNewParams{
    ExtractV2JobCreate: llamacloud.ExtractV2JobCreateParam{
      FileInput: file.ID,
      Configuration: llamacloud.ExtractConfigurationParam{
        DataSchema: dataSchema,
        Tier:       llamacloud.ExtractConfigurationTierAgentic,
      },
    },
  })
  if err != nil {
    log.Fatal(err)
  }

  // Poll until the job reaches a terminal state
  for job.Status == "PENDING" || job.Status == "RUNNING" {
    time.Sleep(2 * time.Second)
    job, err = client.Extract.Get(ctx, job.ID, llamacloud.ExtractGetParams{})
    if err != nil {
      log.Fatal(err)
    }
  }

  fmt.Println(job.ExtractResult.RawJSON())
}

复制为智能体上下文

import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
import ai.llamaindex.llamacloud.core.JsonValue;
import ai.llamaindex.llamacloud.models.extract.ExtractConfiguration;
import ai.llamaindex.llamacloud.models.extract.ExtractCreateParams;
import ai.llamaindex.llamacloud.models.extract.ExtractGetParams;
import ai.llamaindex.llamacloud.models.extract.ExtractV2Job;
import ai.llamaindex.llamacloud.models.extract.ExtractV2JobCreate;
import ai.llamaindex.llamacloud.models.files.FileCreateParams;
import ai.llamaindex.llamacloud.models.files.FileCreateResponse;
import java.nio.file.Paths;
import java.util.Map;

public class ExtractQuickStart {
    public static void main(String[] args) throws Exception {
        LlamaCloudClient client = LlamaCloudOkHttpClient.fromEnv();

        // Define your schema
        ExtractConfiguration.DataSchema dataSchema = ExtractConfiguration.DataSchema.builder()
                .putAdditionalProperty("type", JsonValue.from("object"))
                .putAdditionalProperty("properties", JsonValue.from(Map.of(
                        "name", Map.of("type", "string", "description", "Full name of candidate"),
                        "email", Map.of("type", "string", "description", "Email address"),
                        "skills", Map.of("type", "array", "items", Map.of("type", "string"), "description", "Technical skills"))))
                .build();

        // Upload and extract
        FileCreateResponse file = client.files().create(FileCreateParams.builder()
                .file(Paths.get("resume.pdf"))
                .purpose("extract")
                .build());

        ExtractV2Job job = client.extract().create(ExtractCreateParams.builder()
                .extractV2JobCreate(ExtractV2JobCreate.builder()
                        .fileInput(file.id())
                        .configuration(ExtractConfiguration.builder()
                                .dataSchema(dataSchema)
                                .tier(ExtractConfiguration.Tier.AGENTIC)
                                .build())
                        .build())
                .build());

        // Poll until the job reaches a terminal state
        while (job.status().equals("PENDING") || job.status().equals("RUNNING")) {
            Thread.sleep(2000);
            job = client.extract().get(ExtractGetParams.builder().jobId(job.id()).build());
        }

        System.out.println(job.extractResult());
    }
}

复制为智能体上下文

终端窗口

# Define your schema
SCHEMA='{type: object, properties: {name: {type: string, description: "Full name of candidate"}, email: {type: string, description: "Email address"}, skills: {type: array, items: {type: string}, description: "Technical skills"}}}'

# Upload and extract
FILE_ID=$(llp files create --file resume.pdf --purpose extract | jq -r '.id')
JOB_ID=$(llp extract create \
  --file-input "$FILE_ID" \
  --configuration.tier agentic \
  --configuration.data-schema "$SCHEMA" | jq -r '.id')

# Poll until the job reaches a terminal state
while true; do
  JOB=$(llp extract get --job-id "$JOB_ID") || break
  STATUS=$(printf '%s\n' "$JOB" | jq -r '.status')
  case "$STATUS" in COMPLETED|FAILED|CANCELLED) break ;; esac
  sleep 2
done

printf '%s\n' "$JOB" | jq -r 'if .status == "COMPLETED" then .extract_result
  else "Extract job failed: \(.error_message // .)" end'

完整指南 | 示例 | 配置 Extract

用自然语言规则给文档归类。可作为抽取、解析或建索引前的预处理。

下载一份样例发票,存为 invoice.pdf:

终端窗口

curl -fL -o invoice.pdf https://media.githubusercontent.com/media/run-llama/llama-datasets/main/llama_agents/invoice-contracts/invoice-2-1.pdf

Python(python)

复制为智能体上下文

from llama_cloud import LlamaCloud

client = LlamaCloud()

# Upload a document
file = client.files.create(file="invoice.pdf", purpose="classify")

# Run Classify with natural-language rules and wait for the result
job = client.classify.run(
    file_input=file.id,
    configuration={
        "rules": [
            {
                "type": "invoice",
                "description": "Documents with invoice numbers, line items, and totals",
            },
            {
                "type": "receipt",
                "description": "Short POS receipts with merchant and total",
            },
            {
                "type": "contract",
                "description": "Legal agreements with terms and signatures",
            },
        ],
    },
)

# `run` raises PollingError if the job fails, so reaching here means it succeeded
print(f"Type: {job.result.type}, Confidence: {job.result.confidence}")

复制为智能体上下文

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

const client = new LlamaCloud();

// Upload a document
const file = await client.files.create({
  file: fs.createReadStream('invoice.pdf'),
  purpose: 'classify',
});

// Run Classify with natural-language rules and wait for the result
const job = await client.classify.run({
  file_input: file.id,
  configuration: {
    rules: [
      {
        type: 'invoice',
        description: 'Documents with invoice numbers, line items, and totals',
      },
      {
        type: 'receipt',
        description: 'Short POS receipts with merchant and total',
      },
      {
        type: 'contract',
        description: 'Legal agreements with terms and signatures',
      },
    ],
  },
});

// `run` throws if the job fails, so reaching here means it succeeded
console.log(`Type: ${job.result!.type}, Confidence: ${job.result!.confidence}`);

复制为智能体上下文

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "time"

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

func main() {
  ctx := context.Background()
  client := llamacloud.NewClient()

  // Upload a document
  f, err := os.Open("invoice.pdf")
  if err != nil {
    log.Fatal(err)
  }
  defer f.Close()

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

  // Run Classify with natural-language rules
  job, err := client.Classify.New(ctx, llamacloud.ClassifyNewParams{
    ClassifyCreateRequest: llamacloud.ClassifyCreateRequestParam{
      FileInput: llamacloud.String(file.ID),
      Configuration: llamacloud.ClassifyConfigurationParam{
        Rules: []llamacloud.ClassifyConfigurationRuleParam{
          {Type: "invoice", Description: "Documents with invoice numbers, line items, and totals"},
          {Type: "receipt", Description: "Short POS receipts with merchant and total"},
          {Type: "contract", Description: "Legal agreements with terms and signatures"},
        },
      },
    },
  })
  if err != nil {
    log.Fatal(err)
  }

  // Poll until the job reaches a terminal state
  result, err := client.Classify.Get(ctx, job.ID, llamacloud.ClassifyGetParams{})
  if err != nil {
    log.Fatal(err)
  }
  for result.Status == llamacloud.ClassifyGetResponseStatusPending ||
    result.Status == llamacloud.ClassifyGetResponseStatusRunning {
    time.Sleep(2 * time.Second)
    result, err = client.Classify.Get(ctx, job.ID, llamacloud.ClassifyGetParams{})
    if err != nil {
      log.Fatal(err)
    }
  }

  if !result.JSON.Result.Valid() {
    log.Fatalf("Classification failed: %s", result.ErrorMessage)
  }
  fmt.Printf("Type: %s, Confidence: %v\n", result.Result.Type, result.Result.Confidence)
}

复制为智能体上下文

import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
import ai.llamaindex.llamacloud.models.classify.ClassifyConfiguration;
import ai.llamaindex.llamacloud.models.classify.ClassifyCreateRequest;
import ai.llamaindex.llamacloud.models.classify.ClassifyCreateResponse;
import ai.llamaindex.llamacloud.models.classify.ClassifyGetResponse;
import ai.llamaindex.llamacloud.models.classify.ClassifyResult;
import ai.llamaindex.llamacloud.models.files.FileCreateParams;
import ai.llamaindex.llamacloud.models.files.FileCreateResponse;
import java.nio.file.Paths;
import java.util.Arrays;

public class ClassifyQuickStart {
    public static void main(String[] args) throws Exception {
        LlamaCloudClient client = LlamaCloudOkHttpClient.fromEnv();

        // Upload a document
        FileCreateResponse file = client.files().create(FileCreateParams.builder()
                .file(Paths.get("invoice.pdf"))
                .purpose("classify")
                .build());

        // Run Classify with natural-language rules
        ClassifyCreateResponse job = client.classify().create(ClassifyCreateRequest.builder()
                .fileInput(file.id())
                .configuration(ClassifyConfiguration.builder()
                        .rules(Arrays.asList(
                                ClassifyConfiguration.Rule.builder()
                                        .type("invoice")
                                        .description("Documents with invoice numbers, line items, and totals")
                                        .build(),
                                ClassifyConfiguration.Rule.builder()
                                        .type("receipt")
                                        .description("Short POS receipts with merchant and total")
                                        .build(),
                                ClassifyConfiguration.Rule.builder()
                                        .type("contract")
                                        .description("Legal agreements with terms and signatures")
                                        .build()))
                        .build())
                .build());

        // Poll until the job reaches a terminal state
        ClassifyGetResponse result = client.classify().get(job.id());
        while (result.status().equals(ClassifyGetResponse.Status.PENDING)
                || result.status().equals(ClassifyGetResponse.Status.RUNNING)) {
            Thread.sleep(2000);
            result = client.classify().get(job.id());
        }

        if (result.result().isPresent()) {
            ClassifyResult r = result.result().get();
            System.out.println("Type: " + r.type().orElse("") + ", Confidence: " + r.confidence());
        } else {
            System.out.println("Classification failed: " + result.errorMessage().orElse(""));
        }
    }
}

复制为智能体上下文

终端窗口

# Upload a document
FILE_ID=$(llp files create --file invoice.pdf --purpose classify | jq -r '.id')

# Run Classify with natural-language rules
JOB_ID=$(llp classify create \
  --file-input "$FILE_ID" \
  --configuration '{rules: [{type: invoice, description: "Documents with invoice numbers, line items, and totals"}, {type: receipt, description: "Short POS receipts with merchant and total"}, {type: contract, description: "Legal agreements with terms and signatures"}]}' \
  | jq -r '.id')

# Poll until the job reaches a terminal state
while true; do
  RESULT=$(llp classify get "$JOB_ID") || break
  STATUS=$(printf '%s\n' "$RESULT" | jq -r '.status')
  [ "$STATUS" = "PENDING" ] || [ "$STATUS" = "RUNNING" ] || break
  sleep 2
done

printf '%s\n' "$RESULT" | jq -r 'if .status == "COMPLETED" then .result.type, .result.confidence
  else "Classification failed: \(.error_message // .)" end'

完整指南 | 示例

把拼接在一起的 PDF 切分成逻辑段落。用 AI 驱动的分类来拆分合并的文档。

下载一份包含发票与出口证明的运输单据合集,存为 combined.pdf:

终端窗口

curl -fL -o combined.pdf https://cloud.llamaindex.ai/assets/demos/split/shipping.pdf

Python(python)

复制为智能体上下文

import time

from llama_cloud import LlamaCloud

client = LlamaCloud()

# Upload a combined PDF
file = client.files.create(file="combined.pdf", purpose="split")

# Split into logical sections
job = client.beta.split.create(
    document_input={"type": "file_id", "value": file.id},
    configuration={
        "categories": [
            {
                "name": "invoice",
                "description": "Commercial document with line items and totals"
            },
            {
                "name": "certificate",
                "description": "Certificate of origin or other export certificate"
            },
        ]
    },
)

# Poll until the job reaches a terminal state (Split statuses are lowercase)
result = client.beta.split.get(job.id)
while result.status in ("pending", "processing"):
    time.sleep(2)
    result = client.beta.split.get(job.id)

for segment in result.result.segments:
    print(f"Pages {segment.pages}: {segment.category} ({segment.confidence_category})")

复制为智能体上下文

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

const client = new LlamaCloud();

// Upload a combined PDF
const file = await client.files.create({
  file: fs.createReadStream('combined.pdf'),
  purpose: 'split',
});

// Split into logical sections
const job = await client.beta.split.create({
  document_input: { type: 'file_id', value: file.id },
  configuration: {
    categories: [
      {
        name: 'invoice',
        description: 'Commercial document with line items and totals',
      },
      {
        name: 'certificate',
        description: 'Certificate of origin or other export certificate',
      },
    ],
  },
});

// Poll until the job reaches a terminal state (Split statuses are lowercase)
let result = await client.beta.split.get(job.id);
while (result.status === 'pending' || result.status === 'processing') {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  result = await client.beta.split.get(job.id);
}

for (const segment of result.result.segments) {
  console.log(`Pages ${segment.pages}: ${segment.category} (${segment.confidence_category})`);
}

复制为智能体上下文

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "time"

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

func main() {
  ctx := context.Background()
  client := llamacloud.NewClient()

  // Upload a combined PDF
  f, err := os.Open("combined.pdf")
  if err != nil {
    log.Fatal(err)
  }
  defer f.Close()

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

  // Split into logical sections
  job, err := client.Beta.Split.New(ctx, llamacloud.BetaSplitNewParams{
    DocumentInput: llamacloud.SplitDocumentInputParam{Type: "file_id", Value: file.ID},
    Configuration: llamacloud.BetaSplitNewParamsConfiguration{
      Categories: []llamacloud.SplitCategoryParam{
        {Name: "invoice", Description: llamacloud.String("Commercial document with line items and totals")},
        {Name: "certificate", Description: llamacloud.String("Certificate of origin or other export certificate")},
      },
    },
  })
  if err != nil {
    log.Fatal(err)
  }

  // Poll until the job reaches a terminal state (Split statuses are lowercase)
  result, err := client.Beta.Split.Get(ctx, job.ID, llamacloud.BetaSplitGetParams{})
  if err != nil {
    log.Fatal(err)
  }
  for result.Status == "pending" || result.Status == "processing" {
    time.Sleep(2 * time.Second)
    result, err = client.Beta.Split.Get(ctx, job.ID, llamacloud.BetaSplitGetParams{})
    if err != nil {
      log.Fatal(err)
    }
  }

  for _, segment := range result.Result.Segments {
    fmt.Printf("Pages %v: %s (%s)\n", segment.Pages, segment.Category, segment.ConfidenceCategory)
  }
}

复制为智能体上下文

import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
import ai.llamaindex.llamacloud.models.beta.split.SplitCategory;
import ai.llamaindex.llamacloud.models.beta.split.SplitCreateParams;
import ai.llamaindex.llamacloud.models.beta.split.SplitCreateResponse;
import ai.llamaindex.llamacloud.models.beta.split.SplitDocumentInput;
import ai.llamaindex.llamacloud.models.beta.split.SplitGetResponse;
import ai.llamaindex.llamacloud.models.beta.split.SplitSegmentResponse;
import ai.llamaindex.llamacloud.models.files.FileCreateParams;
import ai.llamaindex.llamacloud.models.files.FileCreateResponse;
import java.nio.file.Paths;

public class SplitQuickStart {
    public static void main(String[] args) throws Exception {
        LlamaCloudClient client = LlamaCloudOkHttpClient.fromEnv();

        // Upload a combined PDF
        FileCreateResponse file = client.files().create(FileCreateParams.builder()
                .file(Paths.get("combined.pdf"))
                .purpose("split")
                .build());

        // Split into logical sections
        SplitCreateResponse job = client.beta().split().create(SplitCreateParams.builder()
                .documentInput(SplitDocumentInput.builder().type("file_id").value(file.id()).build())
                .configuration(SplitCreateParams.Configuration.builder()
                        .addCategory(SplitCategory.builder()
                                .name("invoice")
                                .description("Commercial document with line items and totals")
                                .build())
                        .addCategory(SplitCategory.builder()
                                .name("certificate")
                                .description("Certificate of origin or other export certificate")
                                .build())
                        .build())
                .build());

        // Poll until the job reaches a terminal state (Split statuses are lowercase)
        SplitGetResponse result = client.beta().split().get(job.id());
        while (result.status().equals("pending") || result.status().equals("processing")) {
            Thread.sleep(2000);
            result = client.beta().split().get(job.id());
        }

        for (SplitSegmentResponse segment : result.result().get().segments()) {
            System.out.println("Pages " + segment.pages() + ": " + segment.category()
                    + " (" + segment.confidenceCategory() + ")");
        }
    }
}

复制为智能体上下文

终端窗口

# Upload a combined PDF
FILE_ID=$(llp files create --file combined.pdf --purpose split | jq -r '.id')

# Split into logical sections
JOB_ID=$(llp beta:split create \
  --document-input "{type: file_id, value: $FILE_ID}" \
  --configuration '{categories: [{name: invoice, description: "Commercial document with line items and totals"}, {name: certificate, description: "Certificate of origin or other export certificate"}]}' \
  | jq -r '.id')

# Poll until the job reaches a terminal state (Split statuses are lowercase)
while true; do
  STATUS=$(llp beta:split get --split-job-id "$JOB_ID" | jq -er '.status') || break
  case "$STATUS" in completed|failed|cancelled) break ;; esac
  sleep 2
done

llp beta:split get --split-job-id "$JOB_ID" | jq -rc 'if .status == "completed" then .result.segments[]
  else "Split job failed: \(.error_message // .)" end'

完整指南 | 示例

摄取、切块并嵌入为可检索的索引,为 RAG 与文档智能体的检索供能。Index 的设计是界面优先、配合 SDK 集成。先到 LlamaCloud 控制台创建索引,再做集成:

Python(python)

复制为智能体上下文

from llama_cloud import LlamaCloud

client = LlamaCloud()  # Uses LLAMA_CLOUD_API_KEY env var

# Retrieve relevant nodes from the index
results = client.pipelines.retrieve(
    pipeline_id="your-pipeline-id",
    query="Your query here",
    # -- Customize search behavior --
    # dense_similarity_top_k=20,
    # sparse_similarity_top_k=20,
    # alpha=0.5,
    # -- Control reranking behavior --
    # enable_reranking=True,
    # rerank_top_n=5,
)

for n in results.retrieval_nodes:
    print(f"Score: {n.score}, Text: {n.node.text}")

复制为智能体上下文

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

const client = new LlamaCloud(); // Uses LLAMA_CLOUD_API_KEY env var

// Retrieve relevant nodes from the index
const results = await client.pipelines.retrieve('your-pipeline-id', {
  query: 'Your query here',
  // -- Customize search behavior --
  // dense_similarity_top_k: 20,
  // sparse_similarity_top_k: 20,
  // alpha: 0.5,
  // -- Control reranking behavior --
  // enable_reranking: true,
  // rerank_top_n: 5,
});

for (const node of results.retrieval_nodes || []) {
  console.log(`Score: ${node.score}, Text: ${node.node?.text}`);
}

复制为智能体上下文

package main

import (
  "context"
  "fmt"
  "log"

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

func main() {
  ctx := context.Background()
  client := llamacloud.NewClient() // Uses LLAMA_CLOUD_API_KEY env var

  // Retrieve relevant nodes from the index
  results, err := client.Pipelines.RunSearch(ctx, "your-pipeline-id", llamacloud.PipelineRunSearchParams{
    Query: "Your query here",
    // -- Customize search behavior --
    // DenseSimilarityTopK:  llamacloud.Int(20),
    // SparseSimilarityTopK: llamacloud.Int(20),
    // Alpha:                llamacloud.Float(0.5),
    // -- Control reranking behavior --
    // EnableReranking: llamacloud.Bool(true),
    // RerankTopN:      llamacloud.Int(5),
  })
  if err != nil {
    log.Fatal(err)
  }

  for _, n := range results.RetrievalNodes {
    fmt.Printf("Score: %v, Text: %s\n", n.Score, n.Node.Text)
  }
}

复制为智能体上下文

import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
import ai.llamaindex.llamacloud.models.pipelines.PipelineRetrieveParams;
import ai.llamaindex.llamacloud.models.pipelines.PipelineRetrieveResponse;

public class IndexQuickStart {
    public static void main(String[] args) throws Exception {
        LlamaCloudClient client = LlamaCloudOkHttpClient.fromEnv(); // Uses LLAMA_CLOUD_API_KEY env var

        // Retrieve relevant nodes from the index
        PipelineRetrieveResponse results = client.pipelines().retrieve(
                PipelineRetrieveParams.builder()
                        .pipelineId("your-pipeline-id")
                        .query("Your query here")
                        // -- Customize search behavior --
                        // .denseSimilarityTopK(20)
                        // .sparseSimilarityTopK(20)
                        // .alpha(0.5)
                        // -- Control reranking behavior --
                        // .enableReranking(true)
                        // .rerankTopN(5)
                        .build());

        for (PipelineRetrieveResponse.RetrievalNode n : results.retrievalNodes()) {
            System.out.println("Score: " + n.score().orElse(null) + ", Text: " + n.node().text().orElse(""));
        }
    }
}

复制为智能体上下文

终端窗口

# Retrieve relevant nodes from the index
llp pipelines run-search \
  --pipeline-id "your-pipeline-id" \
  --query "Your query here" \
  | jq -c '.retrieval_nodes[] | {score, text: .node.text}'

# Customize search behavior with --dense-similarity-top-k, --sparse-similarity-top-k,
# --alpha, and control reranking with --enable-reranking and --rerank-top-n.

完整指南 | 示例


LlamaParse 的智能体技能(Agent Skills)

下载技能包

可用的技能

  • llamaparse:面向 PDF、文档、演示与图片的高级解析(图表、表格、内嵌视觉元素)。需要 LLAMA_CLOUD_API_KEY 与 Node 18+。
  • liteparse:本地优先、面向文字密集 PDF 与文档的快速解析。不需要 API key,但需要全局安装 @llamaindex/liteparse 并要求 Node 18+。

安装

用 skills CLI 一次装上这两个技能:

终端窗口

npx skills add run-llama/llamaparse-agent-skills

单技能安装、打包这些技能的智能体插件,以及 Codex 的配置,见技能与插件。


资源

Python SDK pip install "llama-cloud>=2.8"

TypeScript SDK npm install @llamaindex/llama-cloud

Go SDK go get github.com/run-llama/llama-parse-go

Java SDK implementation("ai.llamaindex:llama-cloud:1.3.0")

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

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