文本嵌入

Embeddings for Text (textembedding-gecko) 是支持文本嵌入的模型的名称。文本嵌入是一种 NLP 技术,可将文本数据转换为可由机器学习算法(尤其是大型模型)处理的数值向量。这些向量表示旨在捕获它们所表示字词的语义含义和上下文。

嵌入有多种版本。textembedding-gecko@003 是具有增强的 AI 质量的最新稳定嵌入模型,textembedding-gecko-multilingual@001 是针对各种非英语语言进行了优化的模型。

如需在控制台中探索此模型,请参阅 Model Garden 中的 Embeddings for Text 模型卡片。
前往 Model Garden

使用场景

语义搜索:文本嵌入可用于在高维向量空间中表示用户的查询和文档范围。语义与用户查询更相似的文档在向量空间中的距离会更短,在搜索结果中的排名也会更靠前。

文本分类:训练一个将文本嵌入映射到正确类别标签的模型(例如猫与狗、垃圾邮件与非垃圾邮件)。模型训练完成后,可用于根据嵌入将新文本输入分为一个或多个类别。

HTTP 请求

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/textembedding-gecko:predict

模型版本

如需使用最新的模型版本,请使用 @latest 后缀指定,例如 textembedding-gecko@latest

如需使用稳定的模型版本,请指定模型版本号,例如 textembedding-gecko@003。 每个稳定版本会在后续稳定版发布日期后的六个月内可用。

下表包含可用的稳定模型版本:

textembedding-gecko 模型 发布日期 终止日期
textembedding-gecko@003 2023 年 12 月 12 日 2024 年 10 月 9 日
textembedding-gecko@002 2023 年 11 月 2 日 2024 年 10 月 9 日
textembedding-gecko-multilingual@001 2023 年 11 月 2 日 2024 年 10 月 9 日
textembedding-gecko@001 2023 年 6 月 7 日 2024 年 10 月 9 日
text-embedding-preview-0409 2024 年 4 月 9 日 更新到稳定版。
text-multilingual-embedding-preview-0409 2024 年 4 月 9 日 更新到稳定版。

如需了解详情,请参阅模型版本和生命周期

请求正文

{
  "instances": [
    {
      "task_type": "RETRIEVAL_DOCUMENT",
      "title": "document title",
      "content": "I would like embeddings for this text!"
    },
  ]
}

Vertex AI PaLM Embedding API 执行在线(实时)预测以从输入文本获取嵌入。

该 API 最多可接受 3072 个输入词元,并输出 768 维向量嵌入。对文本嵌入模型 textembedding-gecko 使用以下参数。 如需了解详情,请参阅文本嵌入概览

参数 说明 可接受的值

content

您要为其生成嵌入的文本。 文本

task_type

`task_type` 参数定义为预期的下游应用,可帮助模型生成质量更好的嵌入。它可以是采用以下任一值的字符串。 RETRIEVAL_QUERY, RETRIEVAL_DOCUMENT, SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING, QUESTION_ANSWERING, FACT_VERIFICATION.

title

嵌入的标题。 文本

示例请求

REST

如需使用 Vertex AI API 测试文本提示,请向发布方模型端点发送 POST 请求。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • TEXT:您要为其生成嵌入的文本。

HTTP 方法和网址:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/textembedding-gecko@003:predict

请求 JSON 正文:

{
  "instances": [
    { "content": "TEXT"}
  ],
}

如需发送请求,请选择以下方式之一:

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/publishers/google/models/textembedding-gecko@003:predict"

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/publishers/google/models/textembedding-gecko@003:predict" | Select-Object -Expand Content

您应该会收到类似示例响应的 JSON 响应。

Python

如需了解如何安装或更新 Python,请参阅安装 Python 版 Vertex AI SDK。如需了解详情,请参阅 Python API 参考文档

from typing import List

from vertexai.language_models import TextEmbeddingInput, TextEmbeddingModel

def embed_text(
    texts: List[str] = ["banana muffins? ", "banana bread? banana muffins?"],
    task: str = "RETRIEVAL_DOCUMENT",
    model_name: str = "textembedding-gecko@003",
) -> List[List[float]]:
    """Embeds texts with a pre-trained, foundational model."""
    model = TextEmbeddingModel.from_pretrained(model_name)
    inputs = [TextEmbeddingInput(text, task) for text in texts]
    embeddings = model.get_embeddings(inputs)
    return [embedding.values for embedding in embeddings]

Node.js

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Node.js 设置说明执行操作。如需了解详情,请参阅 Vertex AI Node.js API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

async function main(
  project,
  model = 'textembedding-gecko@003',
  texts = 'banana bread?;banana muffins?',
  task = 'RETRIEVAL_DOCUMENT',
  apiEndpoint = 'us-central1-aiplatform.googleapis.com'
) {
  const aiplatform = require('@google-cloud/aiplatform');
  const {PredictionServiceClient} = aiplatform.v1;
  const {helpers} = aiplatform; // helps construct protobuf.Value objects.
  const clientOptions = {apiEndpoint: apiEndpoint};
  const match = apiEndpoint.match(/(?<Location>\w+-\w+)/);
  const location = match ? match.groups.Location : 'us-centra11';
  const endpoint = `projects/${project}/locations/${location}/publishers/google/models/${model}`;

  async function callPredict() {
    const instances = texts
      .split(';')
      .map(e => helpers.toValue({content: e, taskType: task}));
    const request = {endpoint, instances};
    const client = new PredictionServiceClient(clientOptions);
    const [response] = await client.predict(request);
    console.log('Got predict response');
    const predictions = response.predictions;
    for (const prediction of predictions) {
      const embeddings = prediction.structValue.fields.embeddings;
      const values = embeddings.structValue.fields.values.listValue.values;
      console.log('Got prediction: ' + JSON.stringify(values));
    }
  }

  callPredict();
}

Java

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Java 设置说明执行操作。如需了解详情,请参阅 Vertex AI Java API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import static java.util.stream.Collectors.toList;

import com.google.cloud.aiplatform.v1beta1.EndpointName;
import com.google.cloud.aiplatform.v1beta1.PredictRequest;
import com.google.cloud.aiplatform.v1beta1.PredictResponse;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceSettings;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredictTextEmbeddingsSample {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Details about text embedding request structure and supported models are available in:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/embeddings/get-text-embeddings
    String endpoint = "us-central1-aiplatform.googleapis.com:443";
    String project = "YOUR_PROJECT_ID";
    String model = "textembedding-gecko@003";
    predictTextEmbeddings(
        endpoint,
        project,
        model,
        List.of("banana bread?", "banana muffins?"),
        "RETRIEVAL_DOCUMENT");
  }

  // Gets text embeddings from a pretrained, foundational model.
  public static List<List<Float>> predictTextEmbeddings(
      String endpoint, String project, String model, List<String> texts, String task)
      throws IOException {
    PredictionServiceSettings settings =
        PredictionServiceSettings.newBuilder().setEndpoint(endpoint).build();
    Matcher matcher = Pattern.compile("^(?<Location>\\w+-\\w+)").matcher(endpoint);
    String location = matcher.matches() ? matcher.group("Location") : "us-central1";
    EndpointName endpointName =
        EndpointName.ofProjectLocationPublisherModelName(project, location, "google", model);

    // You can use this prediction service client for multiple requests.
    try (PredictionServiceClient client = PredictionServiceClient.create(settings)) {
      PredictRequest.Builder request =
          PredictRequest.newBuilder().setEndpoint(endpointName.toString());
      for (int i = 0; i < texts.size(); i++) {
        request.addInstances(
            Value.newBuilder()
                .setStructValue(
                    Struct.newBuilder()
                        .putFields("content", valueOf(texts.get(i)))
                        .putFields("taskType", valueOf(task))
                        .build()));
      }
      PredictResponse response = client.predict(request.build());
      List<List<Float>> floats = new ArrayList<>();
      for (Value prediction : response.getPredictionsList()) {
        Value embeddings = prediction.getStructValue().getFieldsOrThrow("embeddings");
        Value values = embeddings.getStructValue().getFieldsOrThrow("values");
        floats.add(
            values.getListValue().getValuesList().stream()
                .map(Value::getNumberValue)
                .map(Double::floatValue)
                .collect(toList()));
      }
      return floats;
    }
  }

  private static Value valueOf(String s) {
    return Value.newBuilder().setStringValue(s).build();
  }
}

响应正文

{
  "predictions": [
    {
      "embeddings": {
        "statistics": {
          "truncated": boolean,
          "token_count": integer
        },
        "values": [ number ]
      }
    }
  ]
}
响应元素 说明
embeddings 根据输入文本生成的结果。
statistics 根据输入文本计算的统计信息。
truncated 表示输入文本是否超过允许的词元数量上限并被截断。
tokenCount 输入文本的词元数。
values values 字段包含与输入文本中的字词对应的嵌入向量。

示例响应

{
  "predictions": [
    {
      "embeddings": {
        "values": [
          0.0058424929156899452,
          0.011848051100969315,
          0.032247550785541534,
          -0.031829461455345154,
          -0.055369812995195389,
          ...
        ],
        "statistics": {
          "token_count": 4,
          "truncated": false
        }
      }
    }
  ]
}