You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Vertex AI文本嵌入响应转换为可读浮点向量?

提取Vertex AI文本嵌入向量的官方方法

你不需要手动编写解码逻辑,Google官方提供的Node.js SDK有两种可靠方式来提取浮点数组形式的嵌入向量,避免API结构变更带来的维护问题:

方式一:使用高阶TextEmbeddingModel(推荐)

这是最简洁且官方推荐的方式,SDK会自动处理响应解析,无需关心底层结构:

  1. 确保安装最新版Vertex AI SDK:
npm install @google-cloud/vertexai
  1. 改写代码使用高阶模型接口:
const {VertexAI} = require('@google-cloud/vertexai');

// 初始化Vertex AI客户端
const vertexAI = new VertexAI({
  project: '你的项目ID',
  location: '你的区域(如us-central1)'
});

// 加载多语言嵌入模型
const embeddingModel = vertexAI.getGenerativeModel({
  model: 'textembedding-gecko-multilingual@latest'
});

async function generateEmbedding(text) {
  const request = {
    content: [{text: text}]
  };

  // 调用嵌入接口,直接获取解析好的向量
  const response = await embeddingModel.embedContent(request);
  const floatVector = response.embedding.values;
  
  console.log('解析后的浮点向量:', floatVector);
  return floatVector;
}

// 调用示例
generateEmbedding('需要生成嵌入的文本内容');

方式二:针对低阶predictionServiceClient的官方解析

如果必须使用低阶客户端,可以借助google-protobuf库的工具类来解析响应:

  1. 安装依赖:
npm install google-protobuf
  1. 添加解析逻辑:
const {Value} = require('google-protobuf/google/protobuf/value_pb');

// 从低阶响应中提取浮点向量
function extractFloatVector(prediction) {
  // 定位到向量所在的listValue
  const listValue = prediction.structValue.fields.values.listValue;
  // 遍历每个元素提取numberValue
  return listValue.values.map(item => item.numberValue);
}

// 在你的原有代码中使用
async function runPrediction() {
  // ... 你的request初始化和predictionServiceClient调用逻辑
  const [response] = await predictionServiceClient.predict(request);
  const predictions = response.predictions;
  
  for (const prediction of predictions) {
    const floatVector = extractFloatVector(prediction);
    console.log('解析后的向量:', floatVector);
  }
}

两种方式都基于官方工具实现,能自动适配API内部结构的变更,比手动解析更可靠。

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:57:49