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

本例我们会保存一份可复用的分类配置,并在多个任务中反复使用它。不必每次都传内联规则,而是创建一次配置、之后按 ID 引用。

当你有一整套标准的分类规则、希望在多个文件间复用或接入自动化流水线时,这很有用。

安装

  • Python
  • TypeScript
  • Go
  • Java
  • CLI

终端窗口

pip install "llama-cloud>=2.8"

终端窗口

npm install @llamaindex/llama-cloud

终端窗口

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

build.gradle.kts

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

终端窗口

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

创建一份已保存的配置

用你的规则创建一份分类配置。它会返回一个可供复用的配置 ID。

SDK 会从你的 API key 解析出所属 project;REST 调用则需要显式的 project ID —— 在界面里打开某个 project 时,URL 中就是它。

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
  • cURL
import os
from llama_cloud import LlamaCloud

client = LlamaCloud(api_key=os.environ["LLAMA_CLOUD_API_KEY"])

config = client.configurations.create(
    name="Invoice vs Receipt Classifier",
    parameters={
        "product_type": "classify_v2",
        "rules": [
            {
                "type": "invoice",
                "description": "Documents that contain an invoice number, invoice date, bill-to section, and line items with totals.",
            },
            {
                "type": "receipt",
                "description": "Short purchase receipts, typically from POS systems, with merchant, items and total, often a single page.",
            },
        ],
        "mode": "FAST",
    },
)

print(config.id)
import LlamaCloud from "@llamaindex/llama-cloud";

const client = new LlamaCloud({
  apiKey: process.env.LLAMA_CLOUD_API_KEY,
});

const config = await client.configurations.create({
  name: "Invoice vs Receipt Classifier",
  parameters: {
    product_type: "classify_v2",
    rules: [
      {
        type: "invoice",
        description:
          "Documents that contain an invoice number, invoice date, bill-to section, and line items with totals.",
      },
      {
        type: "receipt",
        description:
          "Short purchase receipts, typically from POS systems, with merchant, items and total, often a single page.",
      },
    ],
    mode: "FAST",
  },
});

console.log(config.id);
package main

import (
    "context"
    "fmt"
    "log"

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

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

    config, err := client.Configurations.New(ctx, llamacloud.ConfigurationNewParams{
        ConfigurationCreate: llamacloud.ConfigurationCreateParam{
            Name: "Invoice vs Receipt Classifier",
            Parameters: llamacloud.ConfigurationCreateParametersUnionParam{
                OfClassifyV2: &llamacloud.ClassifyV2Parameters{
                    Rules: []llamacloud.ClassifyV2ParametersRule{
                        {
                            Type:        "invoice",
                            Description: "Documents that contain an invoice number, invoice date, bill-to section, and line items with totals.",
                        },
                        {
                            Type:        "receipt",
                            Description: "Short purchase receipts, typically from POS systems, with merchant, items and total, often a single page.",
                        },
                    },
                    Mode: llamacloud.ClassifyV2ParametersModeFast,
                },
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(config.ID)
}
import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
import ai.llamaindex.llamacloud.models.configurations.ClassifyV2Parameters;
import ai.llamaindex.llamacloud.models.configurations.ConfigurationCreate;
import ai.llamaindex.llamacloud.models.configurations.ConfigurationResponse;

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

        ConfigurationResponse config = client.configurations().create(
            ConfigurationCreate.builder()
                .name("Invoice vs Receipt Classifier")
                .parameters(ClassifyV2Parameters.builder()
                    .addRule(ClassifyV2Parameters.Rule.builder()
                        .type("invoice")
                        .description("Documents that contain an invoice number, invoice date, bill-to section, and line items with totals.")
                        .build())
                    .addRule(ClassifyV2Parameters.Rule.builder()
                        .type("receipt")
                        .description("Short purchase receipts, typically from POS systems, with merchant, items and total, often a single page.")
                        .build())
                    .mode(ClassifyV2Parameters.Mode.FAST)
                    .build())
                .build());

        System.out.println(config.id());
    }
}

终端窗口

# llp reads LLAMA_CLOUD_API_KEY from the environment.
CONFIG_ID=$(llp configurations create \
  --name "Invoice vs Receipt Classifier" \
  --parameters '{product_type: classify_v2, rules: [{type: invoice, description: "Documents that contain an invoice number, invoice date, bill-to section, and line items with totals."}, {type: receipt, description: "Short purchase receipts, typically from POS systems, with merchant, items and total, often a single page."}], mode: FAST}' \
  | jq -r '.id')

echo "$CONFIG_ID"

终端窗口

curl -X POST 'https://api.cloud.llamaindex.ai/api/v1/beta/configurations?project_id=YOUR_PROJECT_ID' \
  -H 'accept: application/json' \
  -H "Authorization: Bearer $LLAMA_CLOUD_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Invoice vs Receipt Classifier",
    "parameters": {
      "product_type": "classify_v2",
      "rules": [
        {
          "type": "invoice",
          "description": "Documents that contain an invoice number, invoice date, bill-to section, and line items with totals."
        },
        {
          "type": "receipt",
          "description": "Short purchase receipts, typically from POS systems, with merchant, items and total, often a single page."
        }
      ],
      "mode": "FAST"
    }
  }'

响应里含一个 id 字段 —— 它就是你的 configuration_id:

{
  "id": "cfg-11111111-2222-3333-4444-555555555555",
  "name": "Invoice vs Receipt Classifier",
  "product_type": "classify_v2",
  ...
}

用配置 ID 进行分类

现在用这份已保存的配置来分类文件 —— 不必再内联传规则。

下载示例所用到的那份发票:

终端窗口

curl -fL -o document.pdf https://media.githubusercontent.com/media/run-llama/llama-datasets/main/llama_agents/invoice-contracts/invoice-2-1.pdf
  • Python
  • TypeScript
  • Go
  • Java
  • CLI
import os
import time
from llama_cloud import LlamaCloud

client = LlamaCloud(api_key=os.environ["LLAMA_CLOUD_API_KEY"])

# Look up the configuration created above by name
configs = client.configurations.list(
    name="Invoice vs Receipt Classifier", latest_only=True, product_type=["classify_v2"]
).items
if not configs:
    raise SystemExit('No classify configuration named "Invoice vs Receipt Classifier"')
config_id = configs[0].id

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

# Create a classify job using the saved configuration
job = client.classify.create(
    file_input=file_obj.id,
    configuration_id=config_id,
)

# Poll until complete
status = client.classify.get(job.id)
while status.status in ("PENDING", "RUNNING"):
    time.sleep(2)
    status = client.classify.get(job.id)

# Print result
if status.result:
    print(f"Type: {status.result.type}")
    print(f"Confidence: {status.result.confidence}")
    print(f"Reasoning: {status.result.reasoning}")
else:
    print(f"Classification failed: {status.error_message}")
import LlamaCloud from "@llamaindex/llama-cloud";
import fs from "fs";

const client = new LlamaCloud({
  apiKey: process.env.LLAMA_CLOUD_API_KEY,
});

// Look up the configuration created above by name
const configs = await client.configurations.list({
  name: "Invoice vs Receipt Classifier",
  latest_only: true,
  product_type: ["classify_v2"],
});
if (configs.items.length === 0) {
  throw new Error('No classify configuration named "Invoice vs Receipt Classifier"');
}
const configId = configs.items[0].id;

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

// Create a classify job using the saved configuration
let job = await client.classify.create({
  file_input: fileObj.id,
  configuration_id: configId,
});

// Poll until complete
while (job.status === "PENDING" || job.status === "RUNNING") {
  await new Promise((r) => setTimeout(r, 2000));
  job = await client.classify.get(job.id);
}

// Print result
if (job.result) {
  console.log(`Type: ${job.result.type}`);
  console.log(`Confidence: ${job.result.confidence}`);
  console.log(`Reasoning: ${job.result.reasoning}`);
} else {
  console.log(`Classification failed: ${job.error_message}`);
}
package main

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

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

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

    // Look up the configuration created above by name
    var configID string
    configs := client.Configurations.ListAutoPaging(ctx, llamacloud.ConfigurationListParams{
        Name:        llamacloud.String("Invoice vs Receipt Classifier"),
        LatestOnly:  llamacloud.Bool(true),
        ProductType: []string{"classify_v2"},
    })
    if configs.Next() {
        configID = configs.Current().ID
    }
    if err := configs.Err(); err != nil {
        log.Fatal(err)
    }
    if configID == "" {
        log.Fatal(`no classify configuration named "Invoice vs Receipt Classifier"`)
    }

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

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

    // Create a classify job using the saved configuration
    job, err := client.Classify.New(ctx, llamacloud.ClassifyNewParams{
        ClassifyCreateRequest: llamacloud.ClassifyCreateRequestParam{
            FileInput:       llamacloud.String(fileObj.ID),
            ConfigurationID: llamacloud.String(configID),
        },
    })
    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() {
        fmt.Printf("Classification failed: %s\n", result.ErrorMessage)
    } else {
        fmt.Printf("Type: %s\n", result.Result.Type)
        fmt.Printf("Confidence: %v\n", result.Result.Confidence)
        fmt.Printf("Reasoning: %s\n", result.Result.Reasoning)
    }
}
import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
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.configurations.ConfigurationListPage;
import ai.llamaindex.llamacloud.models.configurations.ConfigurationListParams;
import ai.llamaindex.llamacloud.models.files.FileCreateParams;
import ai.llamaindex.llamacloud.models.files.FileCreateResponse;
import java.nio.file.Paths;

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

        // Look up the configuration created above by name
        ConfigurationListPage configs = client.configurations().list(
            ConfigurationListParams.builder()
                .name("Invoice vs Receipt Classifier")
                .latestOnly(true)
                .addProductType(ConfigurationListParams.ProductType.CLASSIFY_V2)
                .build());
        if (configs.items().isEmpty()) {
            throw new IllegalStateException("No classify configuration named \"Invoice vs Receipt Classifier\"");
        }
        String configId = configs.items().get(0).id();

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

        // Create a classify job using the saved configuration
        ClassifyCreateResponse job = client.classify().create(
            ClassifyCreateRequest.builder()
                .fileInput(fileObj.id())
                .configurationId(configId)
                .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()) {
            System.out.println("Classification failed: " + result.errorMessage().orElse(""));
        } else {
            System.out.println("Type: " + result.result().get().type().orElse(""));
            System.out.println("Confidence: " + result.result().get().confidence());
            System.out.println("Reasoning: " + result.result().get().reasoning());
        }
    }
}

终端窗口

# llp reads LLAMA_CLOUD_API_KEY from the environment.
# Reuse CONFIG_ID from the create step, or look the configuration up by name
CONFIG_ID=${CONFIG_ID:-$(llp configurations list --name "Invoice vs Receipt Classifier" --latest-only \
  --product-type classify_v2 | jq -r '.id' | head -n 1)}

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

# Create a classify job using the saved configuration
JOB_ID=$(llp classify create \
  --file-input "$FILE_ID" \
  --configuration-id "$CONFIG_ID" \
  | 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, .result.reasoning
  else "Classification failed: \(.error_message // .)" end'

更新配置

你可以随时更新已有配置的规则或模式:

  • Python
  • TypeScript
  • Go
  • Java
  • CLI
  • cURL
import os
from llama_cloud import LlamaCloud

client = LlamaCloud(api_key=os.environ["LLAMA_CLOUD_API_KEY"])

# Look up the configuration created above by name
configs = client.configurations.list(
    name="Invoice vs Receipt Classifier", latest_only=True, product_type=["classify_v2"]
).items
if not configs:
    raise SystemExit('No classify configuration named "Invoice vs Receipt Classifier"')
config_id = configs[0].id

config = client.configurations.update(
    config_id,
    parameters={
        "product_type": "classify_v2",
        "rules": [
            {
                "type": "invoice",
                "description": "Documents containing invoice numbers, dates, and itemized totals.",
            },
            {
                "type": "receipt",
                "description": "POS receipts with merchant name, items, and total.",
            },
            {
                "type": "purchase_order",
                "description": "Purchase orders with PO numbers, vendor details, and requested items.",
            },
        ],
        "mode": "FAST",
    },
)

print(config.version)
import LlamaCloud from "@llamaindex/llama-cloud";

const client = new LlamaCloud({
  apiKey: process.env.LLAMA_CLOUD_API_KEY,
});

// Look up the configuration created above by name
const configs = await client.configurations.list({
  name: "Invoice vs Receipt Classifier",
  latest_only: true,
  product_type: ["classify_v2"],
});
if (configs.items.length === 0) {
  throw new Error('No classify configuration named "Invoice vs Receipt Classifier"');
}
const configId = configs.items[0].id;

const config = await client.configurations.update(
  configId,
  {
    parameters: {
      product_type: "classify_v2",
      rules: [
        {
          type: "invoice",
          description:
            "Documents containing invoice numbers, dates, and itemized totals.",
        },
        {
          type: "receipt",
          description: "POS receipts with merchant name, items, and total.",
        },
        {
          type: "purchase_order",
          description:
            "Purchase orders with PO numbers, vendor details, and requested items.",
        },
      ],
      mode: "FAST",
    },
  },
);

console.log(config.version);
package main

import (
    "context"
    "fmt"
    "log"

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

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

    // Look up the configuration created above by name
    var configID string
    configs := client.Configurations.ListAutoPaging(ctx, llamacloud.ConfigurationListParams{
        Name:        llamacloud.String("Invoice vs Receipt Classifier"),
        LatestOnly:  llamacloud.Bool(true),
        ProductType: []string{"classify_v2"},
    })
    if configs.Next() {
        configID = configs.Current().ID
    }
    if err := configs.Err(); err != nil {
        log.Fatal(err)
    }
    if configID == "" {
        log.Fatal(`no classify configuration named "Invoice vs Receipt Classifier"`)
    }

    config, err := client.Configurations.Update(ctx, configID, llamacloud.ConfigurationUpdateParams{
        Parameters: llamacloud.ConfigurationUpdateParamsParametersUnion{
            OfClassifyV2: &llamacloud.ClassifyV2Parameters{
                Rules: []llamacloud.ClassifyV2ParametersRule{
                    {
                        Type:        "invoice",
                        Description: "Documents containing invoice numbers, dates, and itemized totals.",
                    },
                    {
                        Type:        "receipt",
                        Description: "POS receipts with merchant name, items, and total.",
                    },
                    {
                        Type:        "purchase_order",
                        Description: "Purchase orders with PO numbers, vendor details, and requested items.",
                    },
                },
                Mode: llamacloud.ClassifyV2ParametersModeFast,
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(config.Version)
}
import ai.llamaindex.llamacloud.client.LlamaCloudClient;
import ai.llamaindex.llamacloud.client.okhttp.LlamaCloudOkHttpClient;
import ai.llamaindex.llamacloud.models.configurations.ClassifyV2Parameters;
import ai.llamaindex.llamacloud.models.configurations.ConfigurationListPage;
import ai.llamaindex.llamacloud.models.configurations.ConfigurationListParams;
import ai.llamaindex.llamacloud.models.configurations.ConfigurationResponse;
import ai.llamaindex.llamacloud.models.configurations.ConfigurationUpdateParams;

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

        // Look up the configuration created above by name
        ConfigurationListPage configs = client.configurations().list(
            ConfigurationListParams.builder()
                .name("Invoice vs Receipt Classifier")
                .latestOnly(true)
                .addProductType(ConfigurationListParams.ProductType.CLASSIFY_V2)
                .build());
        if (configs.items().isEmpty()) {
            throw new IllegalStateException("No classify configuration named \"Invoice vs Receipt Classifier\"");
        }
        String configId = configs.items().get(0).id();

        ConfigurationResponse config = client.configurations().update(
            ConfigurationUpdateParams.builder()
                .configId(configId)
                .parameters(ClassifyV2Parameters.builder()
                    .addRule(ClassifyV2Parameters.Rule.builder()
                        .type("invoice")
                        .description("Documents containing invoice numbers, dates, and itemized totals.")
                        .build())
                    .addRule(ClassifyV2Parameters.Rule.builder()
                        .type("receipt")
                        .description("POS receipts with merchant name, items, and total.")
                        .build())
                    .addRule(ClassifyV2Parameters.Rule.builder()
                        .type("purchase_order")
                        .description("Purchase orders with PO numbers, vendor details, and requested items.")
                        .build())
                    .mode(ClassifyV2Parameters.Mode.FAST)
                    .build())
                .build());

        System.out.println(config.version());
    }
}

终端窗口

# llp reads LLAMA_CLOUD_API_KEY from the environment.
# Reuse CONFIG_ID from the create step, or look the configuration up by name
CONFIG_ID=${CONFIG_ID:-$(llp configurations list --name "Invoice vs Receipt Classifier" --latest-only \
  --product-type classify_v2 | jq -r '.id' | head -n 1)}

llp configurations update \
  --config-id "$CONFIG_ID" \
  --parameters '{product_type: classify_v2, rules: [{type: invoice, description: "Documents containing invoice numbers, dates, and itemized totals."}, {type: receipt, description: "POS receipts with merchant name, items, and total."}, {type: purchase_order, description: "Purchase orders with PO numbers, vendor details, and requested items."}], mode: FAST}' \
  | jq -r '.version'

终端窗口

curl -X PUT 'https://api.cloud.llamaindex.ai/api/v1/beta/configurations/{CONFIG_ID}?project_id=YOUR_PROJECT_ID' \
  -H 'accept: application/json' \
  -H "Authorization: Bearer $LLAMA_CLOUD_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "parameters": {
      "product_type": "classify_v2",
      "rules": [
        {
          "type": "invoice",
          "description": "Documents containing invoice numbers, dates, and itemized totals."
        },
        {
          "type": "receipt",
          "description": "POS receipts with merchant name, items, and total."
        },
        {
          "type": "purchase_order",
          "description": "Purchase orders with PO numbers, vendor details, and requested items."
        }
      ],
      "mode": "FAST"
    }
  }'

此后使用这个 configuration_id 的分类任务会自动采用更新后的规则。

说明

  • 想把同一套规则复用于多个任务时,用 configuration_id 而不是内联 configuration。
  • 配置归属于你的 project —— 不会跨 project 共享。
  • 你也可以在 LlamaCloud 界面里创建与管理配置。

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