Gestione delle operazioni a lunga esecuzione (LRO)

Le operazioni a lunga esecuzione vengono restituite dalle chiamate al metodo di elaborazione batch perché richiedono più tempo per essere completate rispetto a quello appropriato per una risposta dell'API. In questo modo, il thread chiamante non viene tenuto aperto durante l'elaborazione di molti documenti. L'API Document AI crea un LRO ogni volta che chiami projects.locations.processors.batchProcess tramite l'API o le librerie client. L'LRO monitora lo stato del job di elaborazione.

Puoi utilizzare i metodi delle operazioni forniti dall'API Document AI per verificare lo stato delle LRO. Puoi anche elencare, eseguire il polling o annullare le LRO. Le librerie client chiamano internamente il metodo asincrono poll, abilitando il callback. (Per Python, await è abilitato.) Inoltre, dispongono di un parametro di timeout. All'interno dell'LRO principale restituito da .batchProcess, viene creato un LRO per ogni documento (perché i limiti di conteggio delle pagine in batch sono molto più elevati rispetto alla chiamata di sincronizzazione process e l'elaborazione può richiedere molto tempo). Al termine dell'LRO principale, viene fornito lo stato dettagliato di ogni LRO del documento.

Le LRO vengono gestite a livello di progetto e località Google Cloud . Quando effettui una richiesta all'API, includi il progetto Google Cloud e la località in cui è in esecuzione l'LRO.

Il record di un LRO viene conservato per circa 30 giorni dopo il completamento dell'LRO, il che significa che non puoi visualizzare o elencare un LRO dopo questo periodo.

Visualizzazione dei dettagli di un'operazione a lunga esecuzione

I seguenti esempi mostrano come ottenere dettagli su un'operazione LRO.

REST

Per ottenere lo stato e visualizzare i dettagli di un'LRO, chiama il metodo projects.locations.operations.get.

Supponiamo che tu riceva la seguente risposta dopo aver chiamato projects.locations.processors.batchProcess:

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

Il valore name nella risposta mostra che l'API Document AI ha creato un'LRO denominata projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID.

Puoi anche recuperare il nome dell'LRO elencando le operazioni a lunga esecuzione.

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • PROJECT_ID: l'ID progetto Google Cloud .
  • LOCATION: la posizione in cui è in esecuzione l'LRO, ad esempio:
    • us - Stati Uniti
    • eu - Unione Europea
  • OPERATION_ID: l'ID dell'operazione. L'ID è l'ultimo elemento del nome dell'operazione. Ad esempio:
    • Nome operazione: projects/PROJECT_ID/locations/LOCATION/operations/bc4e1d412863e626
    • ID operazione: bc4e1d412863e626

Metodo HTTP e URL:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Esegui questo comando:

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

Esegui questo comando:

$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

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "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

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Go.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


//go:build examples

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

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Python.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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)

Elenco delle operazioni a lunga esecuzione

Gli esempi seguenti mostrano come elencare le LRO in un progetto e una località Google Cloud .

REST

Per elencare le LRO in un progetto e una località Google Cloud , chiama il metodo projects.locations.operations.list.

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • PROJECT_ID: l'ID progetto Google Cloud .
  • LOCATION: la località in cui sono in esecuzione una o più LRO, ad esempio:
    • us - Stati Uniti
    • eu - Unione Europea
  • FILTER: (Obbligatorio) Query per le LRO da restituire. Opzioni:
    • TYPE: (Obbligatorio) Tipo di LRO da elencare. Opzioni:
      • 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

Metodo HTTP e URL:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Esegui questo comando:

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

Esegui questo comando:

$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

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "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

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Go.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


//go:build examples

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

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Python.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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)

Polling di un'operazione a lunga esecuzione

I seguenti esempi mostrano come eseguire il polling dello stato di un'operazione con esecuzione prolungata.

REST

Per eseguire il polling di un'operazione LRO, chiama ripetutamente il metodo projects.locations.operations.get finché l'operazione non viene completata. Utilizza un backoff tra ogni richiesta di polling, ad esempio 10 secondi.

Prima di utilizzare i dati della richiesta riportati di seguito, apporta le seguenti sostituzioni:

  • PROJECT_ID: il tuo ID progetto Google Cloud
  • LOCATION: la località in cui è in esecuzione l'LRO
  • OPERATION_ID: l'identificatore dell'LRO

Metodo HTTP e URL:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Esegui questo comando per eseguire il polling dello stato di un'operazione LRO ogni 10 secondi:

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

Dovresti ricevere una risposta JSON ogni 10 secondi. Durante l'esecuzione dell'operazione, la risposta conterrà "state": "RUNNING". Al termine dell'operazione, la risposta conterrà "state": "SUCCEEDED" e "done": true.

PowerShell

Esegui questo comando per eseguire il polling dello stato di un'operazione LRO ogni dieci secondi:

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

Dovresti ricevere una risposta JSON ogni 10 secondi. Durante l'esecuzione dell'operazione, la risposta conterrà "state": "RUNNING". Al termine dell'operazione, la risposta conterrà "state": "SUCCEEDED" e "done": true.

Python

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Python.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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)

Annullamento di un'operazione a lunga esecuzione

I seguenti esempi mostrano come annullare un'operazione LRO mentre è in esecuzione.

REST

Per annullare un'LRO, chiama il metodo projects.locations.operations.cancel.

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • PROJECT_ID: l'ID progetto Google Cloud .
  • LOCATION: la posizione in cui è in esecuzione l'LRO, ad esempio:
    • us - Stati Uniti
    • eu - Unione Europea
  • OPERATION_ID: l'ID dell'operazione. L'ID è l'ultimo elemento del nome dell'operazione. Ad esempio:
    • Nome operazione: projects/PROJECT_ID/locations/LOCATION/operations/bc4e1d412863e626
    • ID operazione: bc4e1d412863e626

Metodo HTTP e URL:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Esegui questo comando:

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

Esegui questo comando:

$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

Dovresti ricevere una risposta JSON simile alla seguente:

{}
Se tenti di annullare un'operazione già completata, dovresti ricevere il seguente messaggio di errore:
  "error": {
      "code": 400,
      "message": "Operation has completed and cannot be cancelled: 'PROJECT_ID/locations/LOCATION/operations/OPERATION_ID'.",
      "status": "FAILED_PRECONDITION"
  }

Go

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Go.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


//go:build examples

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

Per saperne di più, consulta la documentazione di riferimento dell'API Document AI Python.

Per eseguire l'autenticazione in Document AI, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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