Batch-Embeddings-Inferenz abrufen

Antworten als Batch zu erhalten ist eine effiziente Art, eine große Anzahl von nicht latenzempfindlichen Anfragen für Embeddings zu senden. Im Gegensatz zu Online-Antworten, bei denen jeweils nur eine Eingabeanfrage gleichzeitig möglich ist, können Sie viele Einbettungsanfragen in einer einzelnen Batchanfrage senden. Ähnlich wie die Batchinferenz für tabellarische Daten in der Gemini Enterprise Agent Platform legen Sie den Ausgabespeicherort fest, fügen Ihre Eingabe hinzu und die Antworten werden asynchron in Ihren Ausgabespeicherort übernommen.

Batchvorhersage für Gemini-Einbettungen

Die Batch-Vorhersage für Gemini Embedding basiert auf Gemini Batch Inference und verwendet ein aktualisiertes Schema für Ein- und Ausgabe:

  • Speicher für Ein- und Ausgaben:Ein- und Ausgaben müssen als JSON Lines-Dateien (JSONL) formatiert sein, die in Cloud Storage gespeichert sind. (BigQuery-Tabellen werden für Gemini-Embedding-Modelle nicht unterstützt.)
  • Joblimits:Jeder Batchjob unterstützt bis zu 1.000.000 Zeilen und eine Eingabedateigröße von bis zu 1 GB.
  • Kontingente und Warteschlangen:Es gibt keine vordefinierten Kontingente für die Nebenläufigkeit. Batchjobs werden dynamisch basierend auf der Ressourcenverfügbarkeit geplant und können bis zu 72 Stunden in der Warteschlange bleiben. Die angestrebte Bearbeitungszeit beträgt weniger als 24 Stunden.

Unterstützte Modelle und Standorte

In der folgenden Tabelle sind die unterstützten Gemini-Embedding-Modelle und ‑Standorte für die Batchinferenz aufgeführt:

Modell Modell-ID Unterstützte Standorte
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 Global (global), US-Multiregion (us), EU-Multiregion (eu)

Weitere Informationen zu regionalen und globalen Endpunkten finden Sie unter Standorte.

Eingaben vorbereiten

Laden Sie Ihre Batch-Eingabedaten als JSONL-Datei in Cloud Storage hoch. Jede Zeile ist ein einzelnes JSON-Objekt, das ein "request"-Feld enthält.

Gemini Embedding 001

Das Modell gemini-embedding-001 unterstützt eine task_type- und title-Konfiguration in embed_content_config für jede Zeile.

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

Das gemini-embedding-2-Modell unterstützt Text-, Bild-, Video- und Audioeingaben. Im Gegensatz zu gemini-embedding-001 werden bei gemini-embedding-2 der Aufgabentyp und der Titel direkt in den Prompt-Text eingefügt. Wenn task_type oder title in embed_content_config übergeben werden, werden sie ignoriert (entsprechend dem Online-API-Verhalten).

Informationen zu Einschränkungen für multimodale Eingaben sowie zu Token- und Dateibeschränkungen finden Sie unter Beschränkungen der Multimodal Embeddings API.

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

Batchantwort anfordern

Abhängig von der Anzahl der Eingabeelemente, die Sie einreichen, kann ein Batchjob einige Zeit in Anspruch nehmen. Sie können einen Batch-Einbettungsjob mit der REST API oder dem Google Gen AI SDK senden.

REST

Sie können mit der REST API einen Batch-Einbettungsjob erstellen. Dazu senden Sie eine POST-Anfrage an den batchPredictionJobs-Endpunkt.

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • ENDPOINT_PREFIX: Das Präfix für die Region oder Multiregion, gefolgt von - (z. B. us-central1-, us- oder eu-). Wenn Sie den Endpunkt global verwenden, lassen Sie das Feld leer (aiplatform.googleapis.com).
  • PROJECT_ID: Die ID Ihres Cloud de Confiance by S3NS -Projekts.
  • LOCATION: Ein unterstützter Standort für das Modell, z. B. us-central1 für gemini-embedding-001 oder global, us oder eu für gemini-embedding-2.
  • BP_JOB_NAME: Ein Anzeigename für Ihren Batchjob.
  • MODEL_ID: Die ID des Publisher-Modells (gemini-embedding-001 oder gemini-embedding-2).
  • INPUT_URI: Der Cloud Storage-URI Ihrer JSONL-Eingabedatei (z. B. gs://my-bucket/path/to/input.jsonl).
  • OUTPUT_URI_PREFIX: Der Cloud Storage-Bucket und das Verzeichnispräfix, in die JSONL-Ausgabedateien geschrieben werden (z. B. gs://my-bucket/path/to/output/).

HTTP-Methode und URL:

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

JSON-Text der Anfrage:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

$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

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

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

Beispiel für curl-Befehle

Die Antwort enthält eine eindeutige Kennung für den Batchjob (BATCH_JOB_ID). Sie können einen Batchjob einreichen und seinen Status mit curl abfragen:

Batchjob erstellen:

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"

Status des Umfrage-Jobs abrufen:

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

Installieren

pip install --upgrade google-genai

Weitere Informationen finden Sie in der SDK-Referenzdokumentation.

Umgebungsvariablen für die Verwendung des Google Gen AI SDK mit Vertex AI festlegen:

# 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

Informationen zum Installieren oder Aktualisieren von Go

Weitere Informationen finden Sie in der SDK-Referenzdokumentation.

Umgebungsvariablen für die Verwendung des Google Gen AI SDK mit Vertex AI festlegen:

# 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

Installieren

npm install @google/genai

Weitere Informationen finden Sie in der SDK-Referenzdokumentation.

Umgebungsvariablen für die Verwendung des Google Gen AI SDK mit Vertex AI festlegen:

# 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

Informationen zum Installieren oder Aktualisieren von Java

Weitere Informationen finden Sie in der SDK-Referenzdokumentation.

Umgebungsvariablen für die Verwendung des Google Gen AI SDK mit Vertex AI festlegen:

# 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;
    }
  }
}

Batchausgabe abrufen

Wenn ein Batchinferenz-Vorgang abgeschlossen ist, werden die JSONL-Ausgabedateien in dem Cloud Storage-Ausgabeverzeichnis gespeichert, das Sie in Ihrer Anfrage angegeben haben.

{"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, ...]}}}

Zusätzliche Ressourcen


Batch-Vorhersage für Legacy-Einbettungen

In diesem Abschnitt werden Batch-Inferenz-Workflows für Legacy-Modelle für Texteinbettungen (text-embedding-004, text-embedding-005 und text-multilingual-embedding-002) beschrieben, die auf einer anderen Architektur als Gemini-Einbettungsmodelle basieren.

Texteinbettungsmodelle, die Batchinferenzen unterstützen

Alle stabilen Versionen von Legacy-Texteinbettungsmodellen unterstützen Batchinferenzen und werden in Produktionsumgebungen vollständig unterstützt. Eine vollständige Liste der Einbettungsmodelle finden Sie unter Einbettungsmodell und -versionen.

Eingaben für Legacy-Modelle vorbereiten

Die Eingabe für Legacy-Batchanfragen ist eine Liste an Prompts, die entweder in einer BigQuery-Tabelle oder als JSON-Lieniendatei (JSONL) in Cloud Storage gespeichert werden können. Jede Anfrage kann bis zu 30.000 Anfragen enthalten.

JSONL-Beispiel

In diesem Abschnitt wird anhand von Beispielen gezeigt, wie Sie JSONL-Eingaben und -Ausgaben für Legacy-Modelle formatieren.

JSONL-Eingabebeispiel
{"content":"Give a short description of a machine learning model:"}
{"content":"Best recipe for banana bread:"}
JSONL-Ausgabebeispiel
{"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":""}

BigQuery-Beispiel

In diesem Abschnitt wird anhand von Beispielen gezeigt, wie Sie BigQuery-Eingaben und -Ausgaben für Legacy-Modelle formatieren.

BigQuery-Eingabebeispiel

Dieses Beispiel zeigt eine BigQuery-Tabelle mit einer einzigen Spalte.

Inhalt
„Kurze Beschreibung eines ML-Modells angeben:”
„Das beste Rezept für Bananenbrot:“
BigQuery-Ausgabebeispiel
Inhalt Vorhersagen Status
„Kurze Beschreibung eines ML-Modells angeben:”
[
  {
    "embeddings": {
      "statistics": {
        "token_count": 8,
        "truncated": false
      },
      "values": [0.1, ...]
    }
  }
]
„Das beste Rezept für Bananenbrot:“
[
  {
    "embeddings": {
      "statistics": {
        "token_count": 3,
        "truncated": false
      },
      "values": [0.2, ...]
    }
  }
]

Batchantwort für Legacy-Modelle anfordern

Abhängig von der Anzahl der Eingabeelemente, die Sie eingereicht haben, kann die Batchvgenerierung eine Weile dauern.

REST

Mit der REST API können Sie Texteinbettungen im Batch für Legacy-Modelle abrufen, indem Sie eine POST-Anfrage an den Endpunkt des Publisher-Modells senden.

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • LOCATION: Der Ort, an den Ihre Anfrage gesendet werden soll (z. B. us-central1).
  • PROJECT_ID: Die ID Ihres Cloud de Confiance by S3NS -Projekts.
  • BP_JOB_NAME: Name des Jobs.
  • MODEL_ID: Die Modell-ID des alten Einbettungsmodells (z. B. text-embedding-005).
  • INPUT_URI: Der URI der Eingabequelle. Dies ist entweder ein BigQuery-Tabellen-URI oder ein JSONL-Datei-URI in Cloud Storage.
  • OUTPUT_URI: Ausgabeziel-URI.

HTTP-Methode und URL:

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

JSON-Text der Anfrage:

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

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

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

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json. Führen Sie folgenden Befehl im Terminal aus, um diese Datei im aktuellen Verzeichnis zu erstellen oder zu überschreiben:

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

Führen Sie dann folgenden Befehl aus, um Ihre REST-Anfrage zu senden:

$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

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

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

Beispiel: cURL-Befehls

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"

Batchausgabe für Legacy-Modelle abrufen

Wenn eine Legacy-Batchinferenz abgeschlossen ist, wird die Ausgabe im Cloud Storage-Bucket oder in der BigQuery-Tabelle gespeichert, die Sie in der Anfrage angegeben haben.

Nächste Schritte