Firebase JS SDK 的 @firebase/ai 版本演进全解:从 VertexAI 0.0.1 到 3.0.0 的破坏性变更与迁移要点
Firebase JS SDK 的 @firebase/ai 版本演进全解:从 VertexAI 0.0.1 到 3.0.0 的破坏性变更与迁移要点
本文以 packages/ai/CHANGELOG.md 为蓝本,完整梳理 @firebase/ai 包从 0.0.1(VertexAI 预览版)到 3.0.0 的每一次版本变更,并结合 backend.ts、constants.ts、requests.ts 等源码,讲清 3.0.0 三大破坏性变更的迁移方法、hybrid 推理的演进脉络,以及升级时需要关注的运行环境与 API 取舍。
1. @firebase/ai 的定位与 changelog 的组织方式
@firebase/ai 是 Firebase JS SDK(本仓库 firebase-js-sdk)中的 AI 组件。根据 packages/ai/README.md 的说明,该包不打算被直接依赖,应仅通过官方支持的 firebase 包间接使用。从 packages/ai/package.json 可以看到其工程事实:
- 当前版本为
3.0.0,main指向dist/index.cjs.js,浏览器端走dist/esm/index.esm.js,Node 端另有独立的 CJS/ESM 入口(./dist/index.node.cjs.js、./dist/index.node.mjs)——这正是 changelog 1.1.0 中"创建 Node CJS 和 ESM 双 bundle"、2.2.0 中"将 ChromeAdapterImpl 代码排除在 Node 入口之外"两条记录对应的产物; engines.node当前要求>=24.12.0(2.0.0 版本曾将最低 Node 版本提升到 20)。
changelog 本身采用 changesets 风格组织:按版本号倒序排列,每个版本分 Major Changes(破坏性变更,对应主版本号)、Minor Changes(新增功能)、Patch Changes(修复)三级,每条变更附 commit 短哈希与 PR 编号,并在涉及依赖联动时列出 Updated dependencies。下文按时间线还原全部 33 个版本的演进,再对关键版本做源码级展开。
2. 版本演进主线:0.0.1 → 3.0.0 全记录
2.1 VertexAI 时代(0.0.1 – 1.4.1)
| 版本 | 级别 | 关键变更 |
|---|---|---|
| 0.0.1 | Patch | 首个预览版 VertexAI SDK 发布 |
| 0.0.2 | Patch | types 路径改为指向 rollup 后的公共 d.ts,修复部分 TypeScript 编译错误 |
| 0.0.3 | Patch | 新增公开的 VertexAIError 类 |
| 0.0.4 | Patch | 依赖联动更新 |
| 1.0.0 | Major | VertexAI in Firebase 正式 GA;移除 ES5 bundle,最低 ES 版本提升至 ES2017 |
| 1.0.1 | Patch | 文档改用新 base URL;VertexAI API Not Enabled 错误去除多余缩进;App Check getToken 出错时发送 dummy token;升级到 TypeScript 5.5.4 |
| 1.0.2 | Patch | 请求完成后清除 fetch timeout,修复 Node 脚本因挂起 timeout 而卡死的问题 |
| 1.0.3 | Patch | 依赖联动更新 |
| 1.0.4 | Patch | FirebaseServerApp 支持直接用 App Check token 初始化(而不必调用 getToken),打通 SSR 环境下 App Check 强制产品的使用 |
| 1.1.0 | Minor | 支持按模态统计 token(modality-based token count);Public Preview:支持 Imagen 3 图像生成 |
| 1.2.0 | Minor | CountTokensRequest 增加 systemInstruction、tools、generationConfig;补齐缺失的 BlockReason 与 FinishReason 枚举值 |
| 1.2.1 | Patch | 在 VertexAI 实例未定义 appId 时初始化模型抛出错误;给 GroundingAttribution 标注废弃 |
| 1.2.2 / 1.2.3 / 1.2.4 | Patch | 依赖联动更新 |
| 1.3.0 | Minor | 支持 Gemini 多模态输出;支持 Gemini Developer API(可走免费额度),并新增 AI API 以适配新产品命名 |
| 1.4.0 | Minor | Schema 支持 minItems / maxItems;Schema builder 增加 title、maximum、minimum、propertyOrdering |
| 1.4.1 | Patch | totalBillableCharacters 标记废弃,建议使用 totalTokens |
这一阶段的主线是:1.3.0 引入 Gemini Developer API 后,产品从"Vertex AI 的 Firebase 封装"过渡为统一的 Firebase AI(AI Logic)能力,为 2.0.0 的产品重构埋下伏笔。
2.2 2.x 时代:产品重构与能力爆发(2.0.0 – 2.16.0)
| 版本 | 级别 | 关键变更 |
|---|---|---|
| 2.0.0 | Major | 支持 anyOf schema;TS 枚举导出改为 const 变量;移除 GroundingAttribution;移除 VertexAI API;新增 Grounding with Google Search、Thinking Budget;Node engines 最低提升到 20;构建目标设为 ES2020;修复 functionDeclaration.parameters 类型 |
| 2.1.0 | Minor | 新增 hybrid 推理(hybrid inference)选项 |
| 2.2.0 | Minor | 支持 Gemini Live API;EnhancedGenerateContentResponse 增加 thoughtSummary() 便捷方法;支持 Firebase App Check 的 limited-use tokens(为未来的 replay protection 做准备);修复 AIError 信息过长;Predict 请求增加 includeSafetyAttributes 字段;Node 入口排除 ChromeAdapterImpl |
| 2.2.1 | Patch | 移除误导出的 factory |
| 2.3.0 | Minor | hybrid 新增 prefer_in_cloud 模式(云端优先,网络失败时回退端侧);新增 Code Execution 功能;组件注册重构;hybrid 文档标签从 EXPERIMENTAL 改为 public preview |
| 2.4.0 | Minor | LiveSession 新增 sendFunctionResponses(并修复音频会话中函数响应导致 WebSocket 断开的缺陷);破坏性变更:StartAudioConversationOptions.functionCallingHandler 必须返回 Promise<FunctionResponse>(因 Live API 处于 Public Preview,允许在 minor 版本引入);新增 URL context 工具(模型可访问公网 URL 内容增强回答);Imagen 生成与 Gemini Developer API 均转 GA;流式响应处理空 parts;Code Execution 标记为 beta |
| 2.5.0 | Minor | 废弃 sendMediaChunks() 与 sendMediaStream(),改用 LiveSession 的 sendTextRealtime()、sendAudioReatime()、sendVideoRealtime();Live API 支持音频转写;generateContent/generateContentStream 响应新增 inferenceSource(标识端侧或云端推理);修复默认 onDeviceParams 与用户参数合并逻辑 |
| 2.6.0 | Minor | 支持服务器提示模板(server prompt templates) |
| 2.6.1 | Patch | 文档链接由 /genai 改为 /ailogic;修复 generateContentStream 返回错误 inferenceSource |
| 2.7.0 | Minor | 支持 AbortSignal,请求可中止;thinkingConfig 支持指定 thinking 级别;默认 hybrid in-cloud 模型更新为 gemini-2.5-flash-lite |
| 2.8.0 | Minor | LiveSession.receive() 返回类型扩展出 LiveServiceGoingAwayNotice(预告服务即将关闭会话);Code Execution 与 URL context 文档移除 preview 标签;隐式缓存场景下 UsageMetadata 增加缓存相关用量参数;hybrid 模式下云端请求增加日志 tag |
| 2.9.0 | Minor | ChatSession 支持自动函数调用(automatic function calling) |
| 2.10.0 | Minor | GenerationConfig 增加 responseJsonSchema |
| 2.11.0 | Minor | Imagen 全系模型宣布废弃(最早 2026 年 6 月下线),替代方案为 Gemini Image 模型("Nano Banana" 系列);hybrid 推理模式下废弃 topK 与 temperature;TemplateGenerativeModel 新增 startChat();服务器提示模板支持自动函数调用与聊天历史;修复用户指定 responseSchema/responseJsonSchema 时模型报错的问题 |
| 2.11.1 | Patch | Code Execution 与 URL context 转 GA;修复 TemplateChatSession 的 TypeScript 构建报错 |
| 2.12.0 | Minor | LiveSession.resumeSession() 支持恢复既有会话;新增 contextWindowCompression 特性;新增 ImageConfig(宽高比与尺寸);FinishReason 取值扩充至模型当前全部取值;支持 Grounding with Google Maps |
| 2.13.0 | Minor | 新增 initializeDeviceModel(),允许 hybrid 模式下显式初始化端侧模型;所有 hybrid 推理特性从 beta(public preview)转正(public / GA) |
| 2.13.1 | Patch | GoogleMaps.enableWidget 废弃(Grounding for Google Maps 服务已公告下线);ChatSession 构造函数中对 params.systemInstruction 套用 formatSystemInstruction() |
| 2.14.0 | Minor | 为非 Live API 模型(如 Gemini TTS 模型)新增文本转语音能力(单说话人与多说话人配置);废弃 VertexAIBackend,改用 AgentPlatformBackend(对应 Vertex AI 更名 Gemini Enterprise Agent Platform);说明两种 backend 默认 region 的差异 |
| 2.15.0 | Minor | 移除 Imagen 相关方法与类型(模型已关停),迁移至 Gemini Image 模型;修复 LanguageModel 检测不正确导致 Chrome 扩展中无法使用端侧模型的问题 |
| 2.16.0 | Minor | 修复函数调用时硬编码非法 function role 导致 gemini-3.6-flash 返回 400 的问题;修复客户端校验误拦截 text/x.enum 的问题(结构化输出现同时接受 application/json 与 text/x.enum) |
2.3 3.0.0:当前版本
3.0.0 的完整变更(与 packages/ai/CHANGELOG.md 顶部条目一一对应):
Major Changes
TemplateGenerativeModel.generateContent与TemplateGenerativeModel.generateContentStream重构为接收统一的TemplateRequest对象({ templateId, templateVariables, toolConfig? })作为第一个参数,且templateVariables在TemplateRequest与StartTemplateChatParams中均为必填;- 移除此前已废弃的 API:删除
VertexAIBackend(以及BackendType.VERTEX_AI),改用AgentPlatformBackend(以及BackendType.AGENT_PLATFORM);同时默认 hybrid in-cloud 模型更新为gemini-3.5-flash-lite; Part重构为带显式type属性的判别联合(discriminated union),引入UnknownPart承载裸 wire 与用户提供的输入,出站(wire egress)时剥离type判别字段,并对聊天历史做防御性深拷贝。
Minor Changes
- 在
GenerationConfig与LiveGenerationConfig中废弃candidateCount、temperature、topP、topK、presencePenalty、frequencyPenalty(Gemini 3.x 及之后模型不支持这些参数); ChatSession改为导出接口(interface)而非类;同时清理 AI Logic 文档注释。
Patch Changes
- 测试套件迁移到 Vitest,并更新 type-only re-exports。
3. 3.0.0 破坏性变更的源码级剖析
3.1 服务器提示模板请求统一为 TemplateRequest
2.6.0 引入服务器提示模板时,generateContent/generateContentStream 的参数形态较为分散;2.11.0 又为 TemplateGenerativeModel 增加了 startChat()(即 StartTemplateChatParams)。3.0.0 将两者统一为单一的 TemplateRequest。在 types/requests.ts 中可以验证其最终结构:
export interface TemplateRequest {
/** 要使用的服务器提示模板 ID */
templateId: string;
/** 用于填充模板的键值对变量 */
templateVariables: Record<string, unknown>;
/** 可选工具配置,服务器提示模板的 unary/streaming generateContent
* 目前仅支持检索/grounding 配置 */
toolConfig?: TemplateToolConfig;
}
注意 templateVariables 是必填字段(无 ?),与 changelog 一致。请求的落点也印证了这一点:template-generative-model.ts 中直接把 request.templateVariables 映射到 wire 请求的 inputs 字段;template-chat-session.ts 在会话请求中同样写入 inputs = this.params.templateVariables。
升级时的实际写法(以 getAI 初始化后为例):
import { getAI } from 'firebase/ai';
const ai = getAI(app);
const model = ai.getGenerativeModel('my-template-id'); // TemplateGenerativeModel
const result = await model.generateContent({
templateId: 'my-template-id',
templateVariables: { topic: 'Firebase', level: 'beginner' }, // 必填
// toolConfig 可选
});
3.2 移除 VertexAIBackend,统一迁移到 AgentPlatformBackend
这是 3.0.0 中影响面最大的变更,其背景是 Vertex AI 更名 Gemini Enterprise Agent Platform。完整时间线为:2.14.0 废弃 VertexAIBackend → 3.0.0 正式删除。
changelog 对迁移差异的官方说明:AgentPlatformBackend 与原 VertexAIBackend 唯一的差别是访问模型的默认 location——前者默认 global,后者默认 us-central1。要在 AgentPlatformBackend 上使用 us-central1,初始化时指定即可:
import { getAI, AgentPlatformBackend } from 'firebase/ai';
// 默认 location 为 'global'
const ai = getAI(app);
// 显式指定 us-central1(注意:多数新 Gemini 模型不支持 us-central1)
const ai2 = getAI(app, { backend: new AgentPlatformBackend('us-central1') });
仓库源码可以精确印证这两点。backend.ts 定义了抽象基类 Backend(含 backendType、_getModelPath、_getTemplatePath),以及两个具体子类:
GoogleAIBackend(Gemini Developer API):模型路径为/${DEFAULT_API_VERSION}/projects/${project}/${model},不含 location 段;AgentPlatformBackend:location字段初始化为DEFAULT_LOCATION,模型路径为/${DEFAULT_API_VERSION}/projects/${project}/locations/${location}/${model}。
而 constants.ts 给出了具体常量:DEFAULT_LOCATION = 'global'、DEFAULT_API_VERSION = 'v1beta'、默认域名 firebasevertexai.googleapis.com。当前源码中已不存在 VertexAIBackend 的任何导出,说明 3.0.0 的移除已完整落地。
同一条 Major 变更中还包含一个容易被忽略的默认值调整:默认 hybrid in-cloud 模型更新为 gemini-3.5-flash-lite。对比 constants.ts:
/**
* Defines the name of the default in-cloud model to use for hybrid inference.
*/
export const DEFAULT_HYBRID_IN_CLOUD_MODEL = 'gemini-3.5-flash-lite';
而 2.7.0 的 changelog 记录当时的默认值是 gemini-2.5-flash-lite。也就是说,升级到 3.0.0 后,未显式指定云端模型的 hybrid 用户会自动换到更新的默认模型,行为上应留意输出差异。
3.3 Part 重构为判别联合类型
2.x 时代,Part 是一个无 type 判别字段的宽松接口,靠 text/inlineData/functionCall 等字段的有无来区分种类。3.0.0 将其改为判别联合,每种 Part 都带显式 type。在 types/content.ts 中:
export type Part =
| TextPart // { type: 'text', text, thought? }
| InlineDataPart // { type: 'inlineData', inlineData, videoMetadata? }
| FunctionCallPart // { type: 'functionCall', functionCall }
| FunctionResponsePart// { type: 'functionResponse', functionResponse }
| FileDataPart
| ExecutableCodePart
| CodeExecutionResultPart;
同文件中还定义了 @internal 的 UnknownPart(content.ts):它是一个"未打标签"的裸 part 结构(text?、inlineData?、functionCall?、functionResponse?、fileData?、executableCode?、codeExecutionResult?、thought? 等字段均可选),用于承载从模型 wire API 收到的原始 part 或调用方直接提供的输入。这与 changelog 的两点描述相互对应:
- 出站剥离
type:wire 协议本身没有type字段,SDK 在序列化出站的Part时会去掉判别属性,保证协议兼容(即type只存在于 SDK 内部类型层); - 聊天历史防御性深拷贝:
ChatSession维护历史时对消息做深拷贝,避免调用方事后修改传入对象污染会话状态。
对使用者的影响:switch (part.type) 的穷举写法现在可以在 TypeScript 中完成完整类型收窄,这是此前宽松接口做不到的。
3.4 3.0.0 其余变更
- 采样参数批量废弃:
candidateCount、temperature、topP、topK、presencePenalty、frequencyPenalty在GenerationConfig与LiveGenerationConfig中同时废弃,原因是 Gemini 3.x 及之后模型不支持这些参数。若你的代码仍在设置这些字段,建议在升级时改为依赖模型默认行为或改用ThinkingConfig等仍受支持的参数(requests.ts 中ThinkingConfig的thinkingBudget文档给出了 0 表示禁用思考等取值语义); ChatSession导出为接口:原先导出ChatSession类,3.0.0 起只导出同名的ChatSession接口。依赖instanceof ChatSession的代码会失效,应改为鸭子类型或ai.startChat()返回值的使用;- 测试基建迁移:Patch 条目将测试套件迁移到 Vitest 并更新 type-only re-exports,仓库中对应的工程文件为 packages/ai/vitest.config.mjs,测试位于 packages/ai/test 与
src/下的*.test.ts(如 template-generative-model.test.ts、template-chat-session.test.ts 已按新的TemplateRequest形态断言templateVariables)。
4. hybrid 推理:贯穿 2.x 的最大特性演进
changelog 中 hybrid 相关条目构成了完整的产品成熟度曲线,值得单列:
| 版本 | 里程碑 |
|---|---|
| 2.1.0 | 引入 hybrid 推理选项(实验性) |
| 2.3.0 | 新增 prefer_in_cloud 模式;文档标签 EXPERIMENTAL → public preview |
| 2.4.0 | Gemini Developer API GA |
| 2.5.0 | 响应新增 inferenceSource,标识端侧/云端推理 |
| 2.6.1 | 修复 generateContentStream 返回错误 inferenceSource |
| 2.7.0 | 默认 in-cloud 模型更新为 gemini-2.5-flash-lite |
| 2.11.0 | hybrid 模式下废弃 topK、temperature |
| 2.13.0 | initializeDeviceModel() 显式初始化端侧模型;hybrid 全部特性转正 GA |
| 2.14.0 | 非 Live API 模型支持 TTS |
| 2.15.0 | 修复 Chrome 扩展中端侧模型不可用的检测缺陷 |
| 3.0.0 | 默认 in-cloud 模型更新为 gemini-3.5-flash-lite |
源码层面的对应实现在 types/enums.ts 与 types/requests.ts:
export const InferenceMode = {
'PREFER_ON_DEVICE': 'prefer_on_device',
'ONLY_ON_DEVICE': 'only_on_device',
'ONLY_IN_CLOUD': 'only_in_cloud',
'PREFER_IN_CLOUD': 'prefer_in_cloud'
} as const;
export interface HybridParams {
/** 指定端侧或云端推理,默认优先端侧 */
mode: InferenceMode;
/** 端侧推理的高级参数 */
onDeviceParams?: OnDeviceParams;
/** 云端推理的高级参数 */
inCloudParams?: ModelParams;
}
注意 InferenceMode 是 const 对象而非 TS 枚举——这是 2.0.0 "Convert TS enums exports into const variables" 这一 Major 变更的直接产物(同样的 const 化改造也作用于 BackendType、FinishReason 等导出)。使用时通过 InferenceMode.PREFER_IN_CLOUD 等属性访问即可,语义与旧枚举兼容,但对做 Object.keys(InferenceMode) 之类反射式用法的代码,键集合保持不变、值类型不变,迁移风险主要在于类型声明层面的 enum → 字面量联合。
配置示例(hybrid 模式,云端优先并在网络错误时回退端侧):
const model = ai.getGenerativeModel('some-model', {
hybrid: {
mode: 'prefer_in_cloud', // 即 InferenceMode.PREFER_IN_CLOUD
inCloudParams: { model: 'gemini-3.5-flash-lite' } // 3.0.0 起不写也是该默认值
}
});
5. 其他重要功能线的演进脉络
Live API(实时会话):2.2.0 引入 → 2.4.0 sendFunctionResponses 与函数调用 handler 返回 Promise<FunctionResponse> 的破坏性修正 → 2.5.0 媒体发送方法换代(sendTextRealtime()/sendAudioReatime()/sendVideoRealtime() 取代 sendMediaChunks()/sendMediaStream())并支持音频转写 → 2.8.0 receive() 可收到 LiveServiceGoingAwayNotice → 2.12.0 resumeSession() 与 contextWindowCompression。
结构化输出:1.4.0 Schema 约束增强 → 2.0.0 支持 anyOf → 2.10.0 GenerationConfig.responseJsonSchema → 2.11.0 修复 responseSchema/responseJsonSchema 导致的模型报错 → 2.16.0 修复 text/x.enum 被误拦截,application/json 与 text/x.enum 均被接受。
Imagen → Gemini Image:1.1.0 Public Preview(Imagen 3)→ 2.4.0 GA → 2.11.0 全系废弃公告(最早 2026 年 6 月关停)→ 2.15.0 方法与类型移除,官方替代为 Gemini Image("Nano Banana")模型。
函数调用:2.9.0 ChatSession 自动函数调用 → 2.11.0 服务器提示模板自动函数调用与聊天历史 → 2.16.0 修复硬编码 function role 在 gemini-3.6-flash 上导致的 400。
安全与鉴权(App Check):1.0.1 getToken 出错时发送 dummy token → 1.0.4 SSR 场景直接以 App Check token 初始化 FirebaseServerApp → 2.2.0 limited-use tokens(为 replay protection 铺路,changelog 建议尽早启用以提升用户覆盖)。
可观测与可用性:2.7.0 AbortSignal 支持请求中止;2.8.0 隐式缓存用量数据进入 UsageMetadata;2.13.1 ChatSession 构造期统一 formatSystemInstruction() 处理系统指令格式。
6. 升级与运行实务清单
基于 changelog 与当前仓库状态,从 2.x 升级到 3.0.0 时建议逐项核对:
- 搜索
VertexAIBackend/BackendType.VERTEX_AI:全部替换为AgentPlatformBackend/BackendType.AGENT_PLATFORM。默认 region 从us-central1变为global(见 backend.ts 与 constants.ts);若业务确需us-central1,显式传new AgentPlatformBackend('us-central1'),但注意多数新 Gemini 模型不支持该 region; - 模板调用改
TemplateRequest:generateContent/generateContentStream的第一个参数改为{ templateId, templateVariables, toolConfig? },templateVariables必填; - 清理已废弃采样参数:
temperature、topP、topK、candidateCount、presencePenalty、frequencyPenalty在 Gemini 3.x 模型上无效,应移除; Part判别联合:按part.type收窄处理;依赖旧宽松形状(直接读part.text)的代码需要补上type分支;ChatSession类型:若代码import { ChatSession }并当作类使用(new或instanceof),改为仅作为类型接口使用;- 运行环境:当前 package.json 要求 Node
>=24.12.0(2.0.0 时最低为 Node 20);构建目标为 ES2020,且 1.0.0 起已无 ES5 bundle(最低 ES2017)——老浏览器/老 Node 环境需先确认再升级; - hybrid 默认模型变化:未显式指定云端模型时,默认从
gemini-2.5-flash-lite(2.7.0 起)变为gemini-3.5-flash-lite,涉及回归测试; - 依赖引入方式:遵循 README 约定,通过官方
firebase包消费本组件,而非直接依赖@firebase/ai。
在仓库内继续深入时,可参考的佐证文件包括:包级 API 审查记录 common/api-review/ai.api.md、各公开类型的 API 文档(如 docs-devsite/ai.agentplatformbackend.md、docs-devsite/ai.backend.md、docs-devsite/ai.templaterequest.md、docs-devsite/ai.starttemplatechatparams.md),以及包自身的 api-extractor.json 与构建/测试配置 rollup.config.js、vitest.config.mjs。
7. 小结
@firebase/ai 的 changelog 完整呈现了一个 AI SDK 产品形态的演化史:0.x–1.x 是 VertexAI 的 Firebase 封装,1.3.0 引入 Gemini Developer API 开启双后端格局,2.x 用两年时间叠出 hybrid 推理、Live API、服务器提示模板、代码执行与 grounding 等能力并完成多轮 GA 转正,3.0.0 则以 TemplateRequest 统一、VertexAIBackend 移除与 Part 判别联合三大破坏性变更完成一次彻底的 API 收敛。上述所有条目均可在 packages/ai/CHANGELOG.md 中逐条对照 commit 与 PR 号追溯,本文引用的类型定义与常量亦可按文中给出的文件路径在当前仓库内直接查证。