Ottenere inferenze di embedding batch

Ricevere risposte batch è un modo per inviare in modo efficiente un gran numero di richieste di incorporamento non sensibili alla latenza. A differenza delle risposte online, in cui puoi inviare una sola richiesta di input alla volta, puoi inviare molte richieste di incorporamento in un'unica richiesta batch. Analogamente a come viene eseguita l'inferenza batch per i dati tabellari in Gemini Enterprise Agent Platform, determini la posizione di output, aggiungi l'input e le risposte vengono inserite in modo asincrono nella posizione di output.

Previsione in batch di Gemini Embedding

La previsione in batch di Gemini Embedding si basa su Gemini Batch Inference e utilizza uno schema aggiornato per input e output:

  • Archiviazione di input e output:gli input e gli output devono essere formattati come file JSON Lines (JSONL) archiviati in Cloud Storage. (Le tabelle BigQuery non sono supportate per i modelli di incorporamento Gemini.)
  • Limiti dei job:ogni job batch supporta fino a 1.000.000 di righe e una dimensione del file di input fino a 1 GB.
  • Quote e accodamento:non esistono quote di concorrenza predefinite. I job batch vengono pianificati dinamicamente in base alla disponibilità delle risorse e possono rimanere in coda fino a 72 ore, con un tempo di risposta target inferiore a 24 ore.

Modelli e località supportati

La tabella seguente elenca i modelli di incorporamento Gemini e le località supportati per l'inferenza batch:

Modello ID modello Località supportate
Gemini Embedding 001 gemini-embedding-001 us-central1, us-east1, us-east4, us-west1, us-west4, europe-west1, europe-west4
Gemini Embedding 2 gemini-embedding-2 Globale (global), multi-regione Stati Uniti (us), multi-regione UE (eu)

Per saperne di più sugli endpoint regionali e globali, consulta Località.

Preparare gli input

Carica i dati di input batch come file JSONL in Cloud Storage, dove ogni riga è un singolo oggetto JSON contenente un campo "request".

Gemini Embedding 001

Il modello gemini-embedding-001 supporta una configurazione task_type e title all'interno di embed_content_config per ogni riga.

{"key": "id_1", "request": {"content": {"parts": [{"text": "Hello World"}]}, "embed_content_config": {"output_dimensionality": 768, "title": "some_title", "task_type": "RETRIEVAL_DOCUMENT"}}}
{"key": "id_2", "request": {"content": {"parts": [{"text": "Hello World again"}]}, "embed_content_config": {"output_dimensionality": 768, "title": "some_title_2", "task_type": "RETRIEVAL_DOCUMENT"}}}

Gemini Embedding 2

Il modello gemini-embedding-2 supporta input di testo, immagini, video e audio. A differenza di gemini-embedding-001, gemini-embedding-2 prevede che il tipo di attività e il titolo siano incorporati direttamente nel testo del prompt. Se task_type o title vengono passati all'interno di embed_content_config, vengono ignorati automaticamente (corrispondono al comportamento dell'API online).

Per i vincoli di input multimodale e i limiti di token e file, consulta Limiti dell'API Multimodal Embeddings.

{"key": "id_1", "request": {"content": {"parts": [{"text": "title: sample | text: Hello World"}]}, "embed_content_config": {"output_dimensionality": 768}}}
{"key": "id_2", "request": {"content": {"parts": [{"fileData": {"fileUri": "gs://cloud-samples-data/generative-ai/image/benchmark.jpeg", "mimeType": "image/jpeg"}}]}, "embed_content_config": {"output_dimensionality": 768}}}

Richiedere una risposta batch

A seconda del numero di elementi di input che invii, il completamento di un job batch può richiedere un po' di tempo. Puoi inviare un job di incorporamento batch utilizzando l'API REST o l'SDK Google Gen AI.

REST

Puoi utilizzare l'API REST per creare un job di incorporamento batch inviando una richiesta POST all'endpoint batchPredictionJobs.

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

  • ENDPOINT_PREFIX: il prefisso della regione o multiregione seguito da - (ad esempio, us-central1-, us- o eu-). Se utilizzi l'endpoint global, lascia vuoto (aiplatform.googleapis.com).
  • PROJECT_ID: l'ID del tuo Cloud de Confiance by S3NS progetto.
  • LOCATION: una località supportata per il modello (ad esempio, us-central1 per gemini-embedding-001 o global, us o eu per gemini-embedding-2).
  • BP_JOB_NAME: un nome visualizzato per il job batch.
  • MODEL_ID: l'ID modello editore (gemini-embedding-001 o gemini-embedding-2).
  • INPUT_URI: l'URI Cloud Storage del file JSONL di input (ad esempio, gs://my-bucket/path/to/input.jsonl).
  • OUTPUT_URI_PREFIX: il bucket Cloud Storage e il prefisso della directory in cui verranno scritti i file JSONL di output (ad esempio, gs://my-bucket/path/to/output/).

Metodo HTTP e URL:

POST https://ENDPOINT_PREFIXaiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/batchPredictionJobs

Corpo JSON della richiesta:

{
  "displayName": "BP_JOB_NAME",
  "model": "publishers/google/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "INPUT_URI"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_URI_PREFIX"
    }
  }
}

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json. Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory corrente:

cat > request.json << 'EOF'
{
  "displayName": "BP_JOB_NAME",
  "model": "publishers/google/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "INPUT_URI"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_URI_PREFIX"
    }
  }
}
EOF

Quindi esegui questo comando per inviare la richiesta REST:

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

PowerShell

Salva il corpo della richiesta in un file denominato request.json. Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory corrente:

@'
{
  "displayName": "BP_JOB_NAME",
  "model": "publishers/google/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "INPUT_URI"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_URI_PREFIX"
    }
  }
}
'@  | Out-File -FilePath request.json -Encoding utf8

Quindi esegui questo comando per inviare la richiesta REST:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://ENDPOINT_PREFIXaiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/batchPredictionJobs" | Select-Object -Expand Content

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BP_JOB_NAME",
  "model": "publishers/google/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "INPUT_URI"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_URI_PREFIX"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2026-09-15T19:33:59.153782Z",
  "updateTime": "2026-09-15T19:33:59.153782Z",
  "modelVersionId": "1"
}

Esempi di comandi curl

La risposta include un identificatore univoco per il job batch (BATCH_JOB_ID). Puoi inviare un job batch e verificare il suo stato utilizzando curl:

Crea un job batch:

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

Stato del job di polling:

curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://ENDPOINT_PREFIXaiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/batchPredictionJobs/BATCH_JOB_ID"

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare SDK Google Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True

import time

from google import genai
from google.genai.types import CreateBatchJobConfig, JobState, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
# TODO(developer): Update and un-comment below line
# output_uri = "gs://your-bucket/your-prefix"

# See the documentation: https://googleapis.github.io/python-genai/genai.html#genai.batches.Batches.create
job = client.batches.create(
    model="gemini-embedding-001",
    # Source link: https://storage.cloud.google.com/cloud-samples-data/generative-ai/embeddings/embeddings_input.jsonl
    src="gs://cloud-samples-data/generative-ai/embeddings/embeddings_input.jsonl",
    config=CreateBatchJobConfig(dest=output_uri),
)
print(f"Job name: {job.name}")
print(f"Job state: {job.state}")
# Example response:
# Job name: projects/.../locations/.../batchPredictionJobs/9876453210000000000
# Job state: JOB_STATE_PENDING

# See the documentation: https://googleapis.github.io/python-genai/genai.html#genai.types.BatchJob
completed_states = {
    JobState.JOB_STATE_SUCCEEDED,
    JobState.JOB_STATE_FAILED,
    JobState.JOB_STATE_CANCELLED,
    JobState.JOB_STATE_PAUSED,
}

while job.state not in completed_states:
    time.sleep(30)
    job = client.batches.get(name=job.name)
    print(f"Job state: {job.state}")
    if job.state == JobState.JOB_STATE_FAILED:
        print(f"Error: {job.error}")
        break

# Example response:
# Job state: JOB_STATE_PENDING
# Job state: JOB_STATE_RUNNING
# Job state: JOB_STATE_RUNNING
# ...
# Job state: JOB_STATE_SUCCEEDED

Go

Scopri come installare o aggiornare Go.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare SDK Google Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"
	"time"

	"google.golang.org/genai"
)

// generateBatchEmbeddings shows how to run a batch embeddings prediction job.
func generateBatchEmbeddings(w io.Writer, outputURI string) error {
	// outputURI = "gs://your-bucket/your-prefix"
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}
	modelName := "gemini-embedding-001"
	// See the documentation: https://pkg.go.dev/google.golang.org/genai#Batches.Create
	job, err := client.Batches.Create(ctx,
		modelName,
		&genai.BatchJobSource{
			Format: "jsonl",
			// Source link: https://storage.cloud.google.com/cloud-samples-data/generative-ai/embeddings/embeddings_input.jsonl
			GCSURI: []string{"gs://cloud-samples-data/generative-ai/embeddings/embeddings_input.jsonl"},
		},
		&genai.CreateBatchJobConfig{
			Dest: &genai.BatchJobDestination{
				Format: "jsonl",
				GCSURI: outputURI,
			},
		},
	)
	if err != nil {
		return fmt.Errorf("failed to create batch job: %w", err)
	}

	fmt.Fprintf(w, "Job name: %s\n", job.Name)
	fmt.Fprintf(w, "Job state: %s\n", job.State)
	// Example response:
	//  Job name: projects/{PROJECT_ID}/locations/us-central1/batchPredictionJobs/9876453210000000000
	//  Job state: JOB_STATE_PENDING

	// See the documentation: https://pkg.go.dev/google.golang.org/genai#BatchJob
	completedStates := map[genai.JobState]bool{
		genai.JobStateSucceeded: true,
		genai.JobStateFailed:    true,
		genai.JobStateCancelled: true,
		genai.JobStatePaused:    true,
	}

	// Poll until job finishes
	for !completedStates[job.State] {
		time.Sleep(30 * time.Second)
		job, err = client.Batches.Get(ctx, job.Name, nil)
		if err != nil {
			return fmt.Errorf("failed to get batch job: %w", err)
		}
		fmt.Fprintf(w, "Job state: %s\n", job.State)

		if job.State == genai.JobStateFailed {
			fmt.Fprintf(w, "Error: %+v\n", job.Error)
			break
		}
	}

	//  Example response:
	//    Job state: JOB_STATE_PENDING
	//    Job state: JOB_STATE_RUNNING
	//    Job state: JOB_STATE_RUNNING
	//    ...
	//    Job state: JOB_STATE_SUCCEEDED

	return nil
}

Node.js

Installa

npm install @google/genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare SDK Google Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION =
  process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';
const OUTPUT_URI = 'gs://your-bucket/your-prefix';

async function runBatchPredictionJob(
  outputUri = OUTPUT_URI,
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
    httpOptions: {
      apiVersion: 'v1',
    },
  });

  // See the documentation: https://googleapis.github.io/js-genai/release_docs/classes/batches.Batches.html
  let job = await client.batches.create({
    model: 'gemini-embedding-001',
    // Source link: https://storage.cloud.google.com/cloud-samples-data/batch/prompt_for_batch_gemini_predict.jsonl
    src: 'gs://cloud-samples-data/generative-ai/embeddings/embeddings_input.jsonl',
    config: {
      dest: outputUri,
    },
  });

  console.log(`Job name: ${job.name}`);
  console.log(`Job state: ${job.state}`);

  // Example response:
  //  Job name: projects/%PROJECT_ID%/locations/us-central1/batchPredictionJobs/9876453210000000000
  //  Job state: JOB_STATE_PENDING

  const completedStates = new Set([
    'JOB_STATE_SUCCEEDED',
    'JOB_STATE_FAILED',
    'JOB_STATE_CANCELLED',
    'JOB_STATE_PAUSED',
  ]);

  while (!completedStates.has(job.state)) {
    await new Promise(resolve => setTimeout(resolve, 30000));
    job = await client.batches.get({name: job.name});
    console.log(`Job state: ${job.state}`);
  }

  // Example response:
  //  Job state: JOB_STATE_PENDING
  //  Job state: JOB_STATE_RUNNING
  //  Job state: JOB_STATE_RUNNING
  //  ...
  //  Job state: JOB_STATE_SUCCEEDED

  return job.state;
}

Java

Scopri come installare o aggiornare Java.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare SDK Google Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True


import static com.google.genai.types.JobState.Known.JOB_STATE_CANCELLED;
import static com.google.genai.types.JobState.Known.JOB_STATE_FAILED;
import static com.google.genai.types.JobState.Known.JOB_STATE_PAUSED;
import static com.google.genai.types.JobState.Known.JOB_STATE_SUCCEEDED;

import com.google.genai.Client;
import com.google.genai.types.BatchJob;
import com.google.genai.types.BatchJobDestination;
import com.google.genai.types.BatchJobSource;
import com.google.genai.types.CreateBatchJobConfig;
import com.google.genai.types.GetBatchJobConfig;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.JobState;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class BatchPredictionEmbeddingsWithGcs {

  public static void main(String[] args) throws InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-embedding-001";
    String outputGcsUri = "gs://your-bucket/your-prefix";
    createBatchJob(modelId, outputGcsUri);
  }

  // Creates a batch prediction job with embedding model and Google Cloud Storage.
  public static JobState createBatchJob(String modelId, String outputGcsUri)
      throws InterruptedException {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("us-central1")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // See the documentation:
      // https://googleapis.github.io/java-genai/javadoc/com/google/genai/Batches.html
      BatchJobSource batchJobSource =
          BatchJobSource.builder()
              // Source link:
              // https://storage.cloud.google.com/cloud-samples-data/generative-ai/embeddings/embeddings_input.jsonl
              .gcsUri("gs://cloud-samples-data/generative-ai/embeddings/embeddings_input.jsonl")
              .format("jsonl")
              .build();

      CreateBatchJobConfig batchJobConfig =
          CreateBatchJobConfig.builder()
              .displayName("your-display-name")
              .dest(BatchJobDestination.builder().gcsUri(outputGcsUri).format("jsonl").build())
              .build();

      BatchJob batchJob = client.batches.create(modelId, batchJobSource, batchJobConfig);

      String jobName =
          batchJob.name().orElseThrow(() -> new IllegalStateException("Missing job name"));
      JobState jobState =
          batchJob.state().orElseThrow(() -> new IllegalStateException("Missing job state"));
      System.out.println("Job name: " + jobName);
      System.out.println("Job state: " + jobState);
      // Job name: projects/.../locations/.../batchPredictionJobs/6205497615459549184
      // Job state: JOB_STATE_PENDING

      // See the documentation:
      // https://googleapis.github.io/java-genai/javadoc/com/google/genai/types/BatchJob.html
      Set<JobState.Known> completedStates =
          EnumSet.of(JOB_STATE_SUCCEEDED, JOB_STATE_FAILED, JOB_STATE_CANCELLED, JOB_STATE_PAUSED);

      while (!completedStates.contains(jobState.knownEnum())) {
        TimeUnit.SECONDS.sleep(30);
        batchJob = client.batches.get(jobName, GetBatchJobConfig.builder().build());
        jobState =
            batchJob
                .state()
                .orElseThrow(() -> new IllegalStateException("Missing job state during polling"));
        System.out.println("Job state: " + jobState);
      }
      // Example response:
      // Job state: JOB_STATE_QUEUED
      // Job state: JOB_STATE_RUNNING
      // ...
      // Job state: JOB_STATE_SUCCEEDED
      return jobState;
    }
  }
}

Recuperare l'output batch

Al termine di un'attività di inferenza batch, i file JSONL di output vengono archiviati nella directory di output di Cloud Storage specificata nella richiesta.

{"key": "id_1", "request": {...}, "response": {"tokenCount": "2", "embedding": {"values": [-0.015, 0.024, ...]}}}
{"key": "id_2", "request": {...}, "response": {"tokenCount": "3", "embedding": {"values": [-0.075, 0.031, ...]}}}

Risorse aggiuntive


Previsioni in batch di incorporamento legacy

Questa sezione descrive i workflow di inferenza batch per i modelli di text embedding legacy (text-embedding-004, text-embedding-005 e text-multilingual-embedding-002), che sono basati su un'architettura diversa rispetto ai modelli di embedding Gemini.

Modelli di text embedding che supportano le inferenze batch

Tutte le versioni stabili dei modelli di text embedding legacy supportano le inferenze batch e sono completamente supportate per gli ambienti di produzione. Per visualizzare l'elenco completo dei modelli di incorporamento, vedi Modelli e versioni di incorporamento.

Preparare gli input per i modelli legacy

L'input per le richieste batch legacy è un elenco di prompt che possono essere archiviati in una tabella BigQuery o come file JSON Lines (JSONL) in Cloud Storage. Ogni richiesta può includere fino a 30.000 prompt.

Esempio di JSONL

Questa sezione mostra esempi di formattazione dell'input e dell'output JSONL per i modelli legacy.

Esempio di input JSONL
{"content":"Give a short description of a machine learning model:"}
{"content":"Best recipe for banana bread:"}
Esempio di output JSONL
{"instance":{"content":"Give..."},"predictions": [{"embeddings":{"statistics":{"token_count":8,"truncated":false},"values":[0.2,....]}}],"status":""}
{"instance":{"content":"Best..."},"predictions": [{"embeddings":{"statistics":{"token_count":3,"truncated":false},"values":[0.1,....]}}],"status":""}

Esempio BigQuery

Questa sezione mostra esempi di come formattare l'input e l'output di BigQuery per i modelli legacy.

Esempio di input BigQuery

Questo esempio mostra una tabella BigQuery a una sola colonna.

contenuti
"Fornisci una breve descrizione di un modello di machine learning:"
"Migliore ricetta per il banana bread:"
Esempio di output BigQuery
contenuti previsioni. stato
"Fornisci una breve descrizione di un modello di machine learning:"
[
  {
    "embeddings": {
      "statistics": {
        "token_count": 8,
        "truncated": false
      },
      "values": [0.1, ...]
    }
  }
]
"Migliore ricetta per il banana bread:"
[
  {
    "embeddings": {
      "statistics": {
        "token_count": 3,
        "truncated": false
      },
      "values": [0.2, ...]
    }
  }
]

Richiedere una risposta batch per i modelli legacy

A seconda del numero di elementi di input che hai inviato, il completamento di un'attività di generazione batch può richiedere un po' di tempo.

REST

Puoi utilizzare l'API REST per ottenere embedding di testo in batch per i modelli legacy inviando una richiesta POST all'endpoint del modello del publisher.

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

  • LOCATION: la località a cui inviare la richiesta (ad esempio, us-central1).
  • PROJECT_ID: l'ID del tuo Cloud de Confiance by S3NS progetto.
  • BP_JOB_NAME: il nome del job.
  • MODEL_ID: l'ID modello del modello di incorporamento legacy (ad esempio text-embedding-005).
  • INPUT_URI: l'URI della sorgente di ingresso. Si tratta di un URI di tabella BigQuery o di un URI di file JSONL in Cloud Storage.
  • OUTPUT_URI: l'URI di destinazione dell'output.

Metodo HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/batchPredictionJobs

Corpo JSON della richiesta:

{
    "name": "BP_JOB_NAME",
    "displayName": "BP_JOB_NAME",
    "model": "publishers/google/models/text-embedding-005",
    "inputConfig": {
      "instancesFormat":"bigquery",
      "bigquerySource":{
        "inputUri" : "INPUT_URI"
      }
    },
    "outputConfig": {
      "predictionsFormat":"bigquery",
      "bigqueryDestination":{
        "outputUri": "OUTPUT_URI"
    }
  }
}

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json. Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory corrente:

cat > request.json << 'EOF'
{
    "name": "BP_JOB_NAME",
    "displayName": "BP_JOB_NAME",
    "model": "publishers/google/models/text-embedding-005",
    "inputConfig": {
      "instancesFormat":"bigquery",
      "bigquerySource":{
        "inputUri" : "INPUT_URI"
      }
    },
    "outputConfig": {
      "predictionsFormat":"bigquery",
      "bigqueryDestination":{
        "outputUri": "OUTPUT_URI"
    }
  }
}

EOF

Quindi esegui questo comando per inviare la richiesta REST:

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

PowerShell

Salva il corpo della richiesta in un file denominato request.json. Esegui questo comando nel terminale per creare o sovrascrivere questo file nella directory corrente:

@'
{
    "name": "BP_JOB_NAME",
    "displayName": "BP_JOB_NAME",
    "model": "publishers/google/models/text-embedding-005",
    "inputConfig": {
      "instancesFormat":"bigquery",
      "bigquerySource":{
        "inputUri" : "INPUT_URI"
      }
    },
    "outputConfig": {
      "predictionsFormat":"bigquery",
      "bigqueryDestination":{
        "outputUri": "OUTPUT_URI"
    }
  }
}

'@  | Out-File -FilePath request.json -Encoding utf8

Quindi esegui questo comando per inviare la richiesta REST:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/batchPredictionJobs" | Select-Object -Expand Content

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/batchPredictionJobs/123456789",
  "displayName": "BP_JOB_NAME",
  "model": "projects/PROJECT_ID/locations/LOCATION/models/text-embedding-005",
  "inputConfig": {
    "instancesFormat": "bigquery",
    "bigquerySource": {
      "inputUri": "INPUT_URI"
    }
  },
  "modelParameters": {},
  "outputConfig": {
    "predictionsFormat": "bigquery",
    "bigqueryDestination": {
      "outputUri": "OUTPUT_URI"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2023-07-12T20:46:52.148717Z",
  "updateTime": "2023-07-12T20:46:52.148717Z",
  "labels": {
    "owner": "sample_owner",
    "product": "llm"
  },
  "modelVersionId": "1",
  "modelMonitoringStatus": {}
}

Comando curl di esempio

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

Recuperare l'output batch per i modelli legacy

Al termine di un'attività di inferenza batch legacy, l'output viene archiviato nel bucket Cloud Storage o nella tabella BigQuery specificati nella richiesta.

Passaggi successivi