取得文字嵌入批次預測結果

本指南說明如何取得文字嵌入的批次預測結果。

如要處理大量對延遲時間不敏感的嵌入要求,建議使用批次預測。批次預測的主要功能包括:

  • 大量:在單一批次作業中處理大量要求,而不是一次處理一個。
  • 非同步處理:與 Vertex AI 中的表格資料批次預測類似,您需要指定結果的輸出位置,這項工作會以非同步方式填入結果。

支援批次預測的文字嵌入模型

所有穩定版文字嵌入模型都支援批次預測。穩定版是指不再是預先發布版,且完全支援正式環境的版本。如要查看支援的嵌入模型完整清單,請參閱「嵌入模型和版本」。

選擇輸入來源

準備輸入內容前,請決定要使用 Cloud Storage 中的 JSONL 檔案,還是 BigQuery 資料表。下表提供比較結果,協助您為用途選擇最佳選項。

輸入來源 說明 用途
Cloud Storage 中的 JSONL 檔案 文字檔,每行都是獨立的 JSON 物件,內含提示。 如果來源資料位於檔案中,或您偏好以檔案為基礎的資料管道,請使用這個選項。
BigQuery 資料表 BigQuery 中的結構化資料表,其中一欄包含提示。 如果提示儲存在 BigQuery 中,或是屬於較大的結構化資料集,請使用這個選項。

準備輸入內容

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

JSONL 格式

輸入範例

輸入檔案中的每一行都必須是有效的 JSON 物件,並含有包含提示的 content 欄位。

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

如要使用 Vertex AI API 測試文字提示,請將 POST 要求傳送至發布商模型端點。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • BP_JOB_NAME:工作名稱。
  • INPUT_URI:輸入來源 URI。這是 BigQuery 資料表 URI 或 Cloud Storage 中的 JSONL 檔案 URI。
  • OUTPUT_URI:輸出目標 URI。

HTTP 方法和網址:

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

JSON 要求主體:

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

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

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

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

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$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://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/batchPredictionJobs" | Select-Object -Expand Content

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

{
  "name": "projects/123456789012/locations/us-central1/batchPredictionJobs/1234567890123456789",
  "displayName": "BP_sample_publisher_BQ_20230712_134650",
  "model": "projects/{PROJECT_ID}/locations/us-central1/models/textembedding-gecko",
  "inputConfig": {
    "instancesFormat": "bigquery",
    "bigquerySource": {
      "inputUri": "bq://project_name.dataset_name.text_input"
    }
  },
  "modelParameters": {},
  "outputConfig": {
    "predictionsFormat": "bigquery",
    "bigqueryDestination": {
      "outputUri": "bq://project_name.llm_dataset.embedding_out_BP_sample_publisher_BQ_20230712_134650"
    }
  },
  "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": {}
}

回應會包含批次作業的專屬 ID。 您可以使用 BATCH_JOB_ID 輪詢批次工作的狀態,直到工作 state 為止。JOB_STATE_SUCCEEDED例如:

curl \
  -X GET \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID

Python

安裝

pip install --upgrade google-genai

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

設定環境變數,透過 Vertex AI 使用 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_VERTEXAI=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="text-embedding-005",
    # 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/%PROJECT_ID%/locations/us-central1/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

擷取批次輸出內容

批次預測工作完成後,系統會根據您的要求,將輸出內容儲存在 Cloud Storage 值區或 BigQuery 資料表中。

後續步驟