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

Firestore更新嵌入向量报错:无法序列化VectorValue对象

问题分析与解决方案

错误原因

你遇到的序列化错误,核心原因有两个:

  1. FieldValue 来源不兼容:当前导入的FieldValue来自@google-cloud/firestore,但在Firebase Functions配合@invertase/firebase-extension-utilities的环境中,需要使用firebase-admin提供的FieldValue——两者的实例原型不同,导致扩展工具无法识别VectorValue对象,触发序列化失败。
  2. 依赖版本可能过低:如果使用的firebase-admin、firebase-functions或@invertase/firebase-extension-utilities版本过旧,可能未适配Firestore的向量搜索功能。

解决方案

方案1:切换到firebase-admin的FieldValue

修改导入语句,替换为firebase-admin提供的FieldValue,并确保初始化admin SDK:

// 替换原导入
import admin from "firebase-admin";
import { FieldValue } from "firebase-admin/firestore";

// 在函数入口初始化admin(确保只初始化一次)
admin.initializeApp();

方案2:升级依赖库版本

确保所有相关依赖版本满足Firestore向量功能要求:

  • firebase-admin >= 11.11.0
  • firebase-functions >= 4.4.0
  • @invertase/firebase-extension-utilities >= 1.6.0(以官方文档为准)

执行版本更新命令:

npm install firebase-admin@latest firebase-functions@latest @invertase/firebase-extension-utilities@latest

方案3:手动处理文档更新(绕过扩展工具自动处理)

如果上述方案无效,直接在embed函数中手动更新文档,避免扩展工具处理VectorValue对象:

import admin from "firebase-admin";
admin.initializeApp();
const db = admin.firestore();

const embed = async (input, context) => {
  await embeddingClient.initialize()
  const text = input[config.inputField]
  let embedding
  try {
    embedding = await embeddingClient.getSingleEmbedding(text)
  } catch (e) {
    console.error("Error fetching embeddings:", e)
    throw new Error("Error with embedding")
  }

  const embeddingVectorAsArray = embedding.slice();
  // 获取文档引用并手动执行更新
  const docRef = db.doc(context.ref.path);
  await docRef.update({
    [config.outputField]: admin.firestore.FieldValue.vector(embeddingVectorAsArray)
  });

  // 返回空对象,阻止扩展工具继续处理
  return {};
}

注:FirestoreOnWriteProcess的回调函数会自动传入包含文档路径的context参数,可直接用于获取文档引用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 12:22:08