長時間実行オペレーション(LRO)の管理

長時間実行オペレーションは、API レスポンスに適した時間よりも完了に時間がかかるため、メソッド呼び出しのバッチ処理によって返されます。これは、多くのドキュメントが処理されている間、呼び出し元のスレッドが開いたままにならないようにするためです。Document AI API は、API またはクライアント ライブラリを介して projects.locations.processors.batchProcess を呼び出すたびに LRO を作成します。LRO は処理ジョブのステータスを追跡します。

Document AI API で提供されるオペレーション メソッドを使用して、LRO のステータスを確認できます。また、LRO の一覧表示ポーリングキャンセルも行えます。非同期メソッドを呼び出すクライアント ライブラリは内部でポーリングし、コールバックを有効にします。(Python の場合は、await が有効になっています)。また、タイムアウト パラメータも用意されています。.batchProcess によって返されたメインの LRO 内で、ドキュメントごとに LRO が作成されます(バッチページ数の上限は同期 process 呼び出しよりもはるかに高く、処理にかなりの時間がかかる可能性があるためです)。メインの LRO が終了すると、各ドキュメントの LRO の詳細なステータスが表示されます。

LRO はプロジェクト レベルとロケーション レベルで管理されます。 Google Cloud API に対してリクエストを行う場合は、プロジェクトと LRO を実行しているロケーションを含めます。 Google Cloud

LRO のレコードは LRO が終了した後、約 30 日間保存されます。それ以降は LRO を表示したり、一覧表示したりできません。

長時間実行オペレーションの詳細の取得

次のサンプルでは、LRO の詳細を取得する方法を示しています。

REST

LRO のステータスを取得し、詳細を確認するには、projects.locations.operations.get メソッドを呼び出します。

projects.locations.processors.batchProcess を呼び出した後に次のレスポンスを受け取ったとします。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID"
}

レスポンスの name 値は、Document AI API が projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID という名前の LRO を作成したことを示しています。

長時間実行オペレーションの一覧表示によって LRO 名を取得することもできます。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION: LRO を実行しているロケーション。次に例を示します。
    • us - 米国
    • eu - 欧州連合
  • OPERATION_ID: オペレーションの ID。この ID は、オペレーションの名前の最後の要素です。例:
    • オペレーション名: projects/PROJECT_ID/locations/LOCATION/operations/bc4e1d412863e626
    • オペレーション ID: bc4e1d412863e626

HTTP メソッドと URL:

GET https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"

PowerShell

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

{
  "name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessMetadata",
    "state": "SUCCEEDED",
    "stateMessage": "Processed 1 document(s) successfully",
    "createTime": "TIMESTAMP",
    "updateTime": "TIMESTAMP",
    "individualProcessStatuses": [
      {
        "inputGcsSource": "INPUT_BUCKET_FOLDER/DOCUMENT1.ext",
        "status": {},
        "outputGcsDestination": "OUTPUT_BUCKET_FOLDER/OPERATION_ID/0",
        "humanReviewStatus": {
          "state": "ERROR",
          "stateMessage": "Sharded document protos are not supported for human review."
        }
      }
    ]
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessResponse"
  }
}

Go

詳細については、Document AI Go API のリファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


package main

import (
	"context"

	documentai "cloud.google.com/go/documentai/apiv1"
	longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := documentai.NewDocumentProcessorClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.GetOperationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/longrunning/autogen/longrunningpb#GetOperationRequest.
	}
	resp, err := c.GetOperation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Python

詳細については、Document AI Python API のリファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import GetOperationRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
# operation_name = "YOUR_OPERATION_NAME"  # Format is "projects/{project_id}/locations/{location}/operations/{operation_id}"


def get_operation_sample(location: str, operation_name: str) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    request = GetOperationRequest(name=operation_name)

    # Make GetOperation request
    operation = client.get_operation(request=request)
    # Print the Operation Information
    print(operation)

長時間実行オペレーションの一覧表示

次のサンプルは、プロジェクトとロケーションで LRO を一覧表示する方法を示しています。 Google Cloud

REST

プロジェクトとロケーションの LRO を一覧表示するには、projects.locations.operations.list メソッドを呼び出します。 Google Cloud

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION: 1 つ以上の LRO を実行しているロケーション。次に例を示します。
    • us - 米国
    • eu - 欧州連合
  • FILTER: (必須)返される LRO のクエリ。オプション:
    • TYPE:(必須)一覧表示する LRO のタイプ。選択肢:
      • BATCH_PROCESS_DOCUMENTS
      • CREATE_PROCESSOR_VERSION
      • DELETE_PROCESSOR
      • ENABLE_PROCESSOR
      • DISABLE_PROCESSOR
      • UPDATE_HUMAN_REVIEW_CONFIG
      • HUMAN_REVIEW_EVENT
      • CREATE_LABELER_POOL
      • UPDATE_LABELER_POOL
      • DELETE_LABELER_POOL
      • DEPLOY_PROCESSOR_VERSION
      • UNDEPLOY_PROCESSOR_VERSION
      • DELETE_PROCESSOR_VERSION
      • SET_DEFAULT_PROCESSOR_VERSION
      • EVALUATE_PROCESSOR_VERSION
      • EXPORT_PROCESSOR_VERSION
      • UPDATE_DATASET
      • IMPORT_DOCUMENTS
      • ANALYZE_HITL_DATA
      • BATCH_MOVE_DOCUMENTS
      • RESYNC_DATASET
      • BATCH_DELETE_DOCUMENTS
      • DELETE_DATA_LABELING_JOB
      • EXPORT_DOCUMENTS

HTTP メソッドと URL:

GET https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations?filter=TYPE=TYPE

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations?filter=TYPE=TYPE"

PowerShell

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations?filter=TYPE=TYPE" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

{
  "operations": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessMetadata",
        "state": "SUCCEEDED",
        "stateMessage": "Processed 1 document(s) successfully",
        "createTime": "TIMESTAMP",
        "updateTime": "TIMESTAMP",
        "individualProcessStatuses": [
          {
            "inputGcsSource": "INPUT_BUCKET_FOLDER/DOCUMENT1.ext",
            "status": {},
            "outputGcsDestination": "OUTPUT_BUCKET_FOLDER/OPERATION_ID/0",
            "humanReviewStatus": {
              "state": "ERROR",
              "stateMessage": "Sharded document protos are not supported for human review."
            }
          }
        ]
      },
      "done": true,
      "response": {
        "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessResponse"
      }
    },
    ...
  ]
}

Go

詳細については、Document AI Go API のリファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


package main

import (
	"context"

	documentai "cloud.google.com/go/documentai/apiv1"
	longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb"
	"google.golang.org/api/iterator"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := documentai.NewDocumentProcessorClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.ListOperationsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/longrunning/autogen/longrunningpb#ListOperationsRequest.
	}
	it := c.ListOperations(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp

		// If you need to access the underlying RPC response,
		// you can do so by casting the `Response` as below.
		// Otherwise, remove this line. Only populated after
		// first call to Next(). Not safe for concurrent access.
		_ = it.Response.(*longrunningpb.ListOperationsResponse)
	}
}

Python

詳細については、Document AI Python API のリファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import ListOperationsRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"

# Create filter in https://google.aip.dev/160 syntax
# For full options, refer to:
# https://cloud.google.com/document-ai/docs/long-running-operations#listing_long-running_operations
# operations_filter = 'YOUR_FILTER'

# Example:
# operations_filter = "TYPE=BATCH_PROCESS_DOCUMENTS AND STATE=RUNNING"


def list_operations_sample(
    project_id: str, location: str, operations_filter: str
) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    # Format: `projects/{project_id}/locations/{location}`
    name = client.common_location_path(project=project_id, location=location)
    request = ListOperationsRequest(
        name=f"{name}/operations",
        filter=operations_filter,
    )

    # Make ListOperations request
    operations = client.list_operations(request=request)

    # Print the Operation Information
    print(operations)

長時間実行オペレーションのポーリング

次のサンプルでは、LRO のステータスをポーリングする方法を示しています。

REST

LRO をポーリングするには、オペレーションが完了するまで projects.locations.operations.get メソッドを繰り返し呼び出します。各ポーリング リクエスト間でバックオフ(たとえば、10 秒)を使用します。

後述のリクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: プロジェクト ID Google Cloud
  • LOCATION: LRO を実行しているロケーション
  • OPERATION_ID:LRO の識別子

HTTP メソッドと URL:

GET https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID
  

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行して、10 秒ごとに LRO のステータスをポーリングします。

while true; \
    do curl -X GET \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"; \
    sleep 10; \
    done

10 秒ごとに JSON レスポンスが返されます。オペレーションの実行中、レスポンスに "state": "RUNNING" が含まれます。オペレーションが終了すると、レスポンスに "state": "SUCCEEDED""done": true が含まれます。

PowerShell

次のコマンドを実行して、10 秒ごとに LRO のステータスをポーリングします。

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Do {
  Invoke-WebRequest `
    -Method Get `
    -Headers $headers `
    -Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID" | Select-Object -Expand Content
sleep 10
}

while ($true)

10 秒ごとに JSON レスポンスが返されます。オペレーションの実行中、レスポンスに "state": "RUNNING" が含まれます。オペレーションが終了すると、レスポンスに "state": "SUCCEEDED""done": true が含まれます。

Python

詳細については、Document AI Python API のリファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


from time import sleep

from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import GetOperationRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
# operation_name = "YOUR_OPERATION_NAME"  # Format is "projects/{project_id}/locations/{location}/operations/{operation_id}"


def poll_operation_sample(location: str, operation_name: str) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    request = GetOperationRequest(name=operation_name)

    while True:
        # Make GetOperation request
        operation = client.get_operation(request=request)
        # Print the Operation Information
        print(operation)

        # Stop polling when Operation is no longer running
        if operation.done:
            break

        # Wait 10 seconds before polling again
        sleep(10)

長時間実行オペレーションのキャンセル

以下のサンプルでは、LRO の実行中に LRO をキャンセルする方法を示しています。

REST

LRO をキャンセルするには、projects.locations.operations.cancel メソッドを呼び出します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION: LRO を実行しているロケーション。次に例を示します。
    • us - 米国
    • eu - 欧州連合
  • OPERATION_ID: オペレーションの ID。この ID は、オペレーションの名前の最後の要素です。例:
    • オペレーション名: projects/PROJECT_ID/locations/LOCATION/operations/bc4e1d412863e626
    • オペレーション ID: bc4e1d412863e626

HTTP メソッドと URL:

POST https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID:cancel

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d "" \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID:cancel"

PowerShell

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID:cancel" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

{}
完了したオペレーションをキャンセルしようとすると、次のエラー メッセージが表示されます。
  "error": {
      "code": 400,
      "message": "Operation has completed and cannot be cancelled: 'PROJECT_ID/locations/LOCATION/operations/OPERATION_ID'.",
      "status": "FAILED_PRECONDITION"
  }

Go

詳細については、Document AI Go API のリファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


package main

import (
	"context"

	documentai "cloud.google.com/go/documentai/apiv1"
	longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := documentai.NewDocumentProcessorClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.CancelOperationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/longrunning/autogen/longrunningpb#CancelOperationRequest.
	}
	err = c.CancelOperation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
}

Python

詳細については、Document AI Python API のリファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import CancelOperationRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
# operation_name = "YOUR_OPERATION_NAME"  # Format is "projects/{project_id}/locations/{location}/operations/{operation_id}"


def cancel_operation_sample(location: str, operation_name: str) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    request = CancelOperationRequest(name=operation_name)

    # Make CancelOperation request
    client.cancel_operation(request=request)
    print(f"Operation {operation_name} cancelled")