取得批次嵌入推論結果

取得批次回應可有效率地傳送大量對延遲時間不敏感的嵌入要求。與線上回覆不同,您一次只能發出一項輸入要求,但可以透過單一批次要求傳送多個嵌入要求。與在 Gemini Enterprise Agent Platform 中對表格資料執行批次推論類似,您需要決定輸出位置、新增輸入內容,然後系統會將回覆非同步填入輸出位置。

Gemini Embedding 批次預測

Gemini Embedding 批次預測是以 Gemini 批次推論為基礎,並使用更新的輸入和輸出結構定義:

  • 輸入和輸出儲存空間:輸入和輸出內容必須格式化為 JSON Lines (JSONL) 檔案,並儲存在 Cloud Storage 中。(Gemini 嵌入模型不支援 BigQuery 資料表)。
  • 工作限制:每個批次工作最多支援 1,000,000 列,輸入檔案大小上限為 1 GB。
  • 配額和佇列:沒有預先定義的並行配額。系統會根據資源可用性動態排定批次工作,且工作最多可保留在佇列中 72 小時,目標是將周轉時間控制在 24 小時內。

支援的機型和地區

下表列出支援的 Gemini 嵌入模型,以及批次推論適用的位置:

模型 模型 ID 支援的地區
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)、美國多區域 (us)、 歐盟多區域 (eu)

如要進一步瞭解區域和全域端點,請參閱「位置」。

準備輸入內容

將批次輸入資料以 JSONL 檔案形式上傳至 Cloud Storage,其中每行都是包含 "request" 欄位的單一 JSON 物件。

Gemini Embedding 001

gemini-embedding-001 模型支援每個資料列的 embed_content_config 內 task_type 和 title 設定。

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

gemini-embedding-2 模型支援文字、圖片、影片和音訊輸入內容。與 gemini-embedding-001 不同,gemini-embedding-2 會直接在提示文字中內嵌工作類型和標題。如果 task_type 或 title 是在 embed_content_config 內傳遞,系統會自動忽略這些值 (與線上 API 行為相符)。

如要瞭解多模態輸入限制,以及詞元和檔案限制,請參閱「多模態嵌入 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}}}

要求批次回應

視提交的輸入項目數量而定,批次工作可能需要一些時間才能完成。您可以使用 REST API 或 Google Gen AI SDK 提交批次嵌入工作。

REST

如要使用 REST API 建立批次嵌入作業,請向 batchPredictionJobs 端點傳送 POST 要求。

使用任何要求資料之前,請先修改下列項目的值:

  • ENDPOINT_PREFIX:區域或多區域前置字串,後接 - (例如 us-central1-、us- 或 eu-)。如果使用 global 端點,請留空 (aiplatform.googleapis.com)。
  • PROJECT_ID:專案的 ID。 Cloud de Confiance by S3NS
  • LOCATION:模型支援的位置 (例如 gemini-embedding-001 的 us-central1,或 gemini-embedding-2 的 global、us 或 eu)。
  • BP_JOB_NAME:批次工作的顯示名稱。
  • MODEL_ID:發布商模型 ID (gemini-embedding-001 或 gemini-embedding-2)。
  • INPUT_URI:輸入 JSONL 檔案的 Cloud Storage URI (例如 gs://my-bucket/path/to/input.jsonl)。
  • OUTPUT_URI_PREFIX:要寫入輸出 JSONL 檔案的 Cloud Storage bucket 和目錄前置字元 (例如 gs://my-bucket/path/to/output/)。

HTTP 方法和網址:

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

JSON 要求內文:

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

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中。 在終端機中執行下列指令,在目前目錄中建立或覆寫這個檔案:

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

然後執行下列指令,傳送 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

將要求主體儲存在名為 request.json 的檔案中。 在終端機中執行下列指令,在目前目錄中建立或覆寫這個檔案:

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

然後執行下列指令,傳送 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

您應該會收到如下的 JSON 回覆:

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

curl 指令範例

回應會包含批次工作專屬 ID (BATCH_JOB_ID)。您可以提交批次工作,並使用 curl 輪詢其狀態:

建立批次工作:

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"

輪詢工作狀態:

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

安裝

pip install --upgrade google-genai

詳情請參閱 SDK 參考文件。

設定環境變數,透過 Vertex AI 使用 Google Gen AI SDK:

# 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

瞭解如何安裝或更新 Go。

詳情請參閱 SDK 參考文件。

設定環境變數,透過 Vertex AI 使用 Google Gen AI SDK:

# 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

安裝

npm install @google/genai

詳情請參閱 SDK 參考文件。

設定環境變數,透過 Vertex AI 使用 Google Gen AI SDK:

# 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

瞭解如何安裝或更新 Java。

詳情請參閱 SDK 參考說明文件。

設定環境變數,透過 Vertex AI 使用 Google Gen AI SDK:

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

擷取批次輸出內容

批次推論工作完成後,系統會將輸出 JSONL 檔案儲存在您在要求中指定的 Cloud Storage 輸出目錄。

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

其他資源


舊版 Embedding 批次預測

本節說明舊版文字嵌入模型 (text-embedding-004、text-embedding-005 和 text-multilingual-embedding-002) 的批次推論工作流程,這些模型與 Gemini 嵌入模型採用不同的架構。

支援批次推論的文字嵌入模型

所有舊版文字嵌入模型穩定版都支援批次推論,且完全支援正式環境。如要查看完整的嵌入模型清單,請參閱「嵌入模型和版本」。

準備舊版模型的輸入內容

舊版批次要求的輸入內容是提示清單,可儲存在 BigQuery 資料表中,或以 JSON Lines (JSONL) 檔案形式儲存在 Cloud Storage 中。每項要求最多可包含 30,000 個提示。

JSONL 範例

本節提供範例,說明如何設定舊版模型的 JSONL 輸入和輸出格式。

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

BigQuery 範例

本節將以範例說明如何為舊版模型設定 BigQuery 輸入和輸出格式。

BigQuery 輸入內容範例

這個範例顯示單一資料欄的 BigQuery 資料表。

內容
「簡要說明機器學習模型:」
「香蕉麵包最佳食譜:」
BigQuery 輸出範例
內容 預測 狀態
「簡要說明機器學習模型:」
[
  {
    "embeddings": {
      "statistics": {
        "token_count": 8,
        "truncated": false
      },
      "values": [0.1, ...]
    }
  }
]
「香蕉麵包最佳食譜:」
[
  {
    "embeddings": {
      "statistics": {
        "token_count": 3,
        "truncated": false
      },
      "values": [0.2, ...]
    }
  }
]

要求舊版模型的批次回應

視提交的輸入項目數量而定,批次生成作業可能需要一些時間才能完成。

REST

您可以向發布者模型端點傳送 POST 要求,使用 REST API 批次取得舊版模型的文字嵌入。

使用任何要求資料之前,請先修改下列項目的值:

  • LOCATION:傳送要求的地點 (例如 us-central1)。
  • PROJECT_ID:專案的 ID。 Cloud de Confiance by S3NS
  • BP_JOB_NAME:工作名稱。
  • MODEL_ID:舊版嵌入模型的模型 ID (例如 text-embedding-005)。
  • INPUT_URI:輸入來源 URI。這是 BigQuery 資料表 URI 或 Cloud Storage 中的 JSONL 檔案 URI。
  • OUTPUT_URI:輸出目標 URI。

HTTP 方法和網址:

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

JSON 要求內文:

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

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中。 在終端機中執行下列指令,在目前目錄中建立或覆寫這個檔案:

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

然後執行下列指令,傳送 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

將要求主體儲存在名為 request.json 的檔案中。 在終端機中執行下列指令,在目前目錄中建立或覆寫這個檔案:

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

然後執行下列指令,傳送 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

您應該會收到如下的 JSON 回覆:

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

cURL 指令範例

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"

擷取舊版模型的批次輸出內容

舊版批次推論工作完成後,系統會根據您的要求,將輸出內容儲存在指定的 Cloud Storage bucket 或 BigQuery 資料表中。

後續步驟