Firebase AI SDK `Backend` 类完全解析:抽象 Gemini Developer API 与 Agent Platform 双后端配置体系
Firebase AI SDK Backend 类完全解析:抽象 Gemini Developer API 与 Agent Platform 双后端配置体系
Backend 是 Firebase JS SDK 中 AI 模块(@firebase/ai,源码位于 packages/ai)的核心抽象基类,它把"AI 服务后端"这一概念封装为可配置、可扩展的类体系,让上层 API 无需关心底层请求细节。本文基于官方 API 参考文档 ai.backend.md,结合仓库源码与测试用例,系统讲解 Backend 的类设计、两个官方子类 GoogleAIBackend 与 AgentPlatformBackend 的差异、BackendType 常量体系,以及它们如何通过 getAI() 和 AIOptions 进入实际请求链路——读完你可以准确理解 Firebase AI SDK 支持哪几种 Gemini 后端、如何选择、如何配置区域,以及后端选择如何影响最终发出的 API 请求路径。
Backend 类的定位与设计意图
从 backend.ts 的源码可以看到,Backend 被声明为 abstract class,即抽象基类:
export abstract class Backend {
readonly backendType: BackendType;
protected constructor(type: BackendType) {
this.backendType = type;
}
abstract _getModelPath(project: string, model: string): string;
abstract _getTemplatePath(project: string, templateId: string): string;
}
其设计意图非常明确(文档原文):
Abstract base class representing the configuration for an AI service backend. This class should not be instantiated directly.
即:Backend 代表"某个 AI 服务后端的配置",不应被直接实例化。官方明确要求通过它的子类来使用:
GoogleAIBackend:面向 Gemini Developer API(经由 Google AI);AgentPlatformBackend:面向 Agent Platform Gemini API(即原来的 Vertex AI Gemini API)。
从面向对象的角度看,这是一个典型的"策略模式 + 抽象基类"组合:SDK 的其余代码(模型类、请求构造器)只依赖 Backend 这一抽象类型,具体是哪个后端、路径怎么拼,全部由子类多态实现。这样做的直接收益是:新增一种后端服务时,无需改动任何模型调用代码,只需新增一个 Backend 子类。
需要特别说明的是,_getModelPath 与 _getTemplatePath 两个方法在源码注释中被标记为 @internal,它们是 SDK 内部构造 REST 请求路径用的钩子,不属于面向开发者公开调用的 API,文档化的公开签名只有构造器与 backendType 属性。
类签名与公开成员
官方 API 参考文档给出的 Backend 类签名为:
export declare abstract class Backend
它对外暴露两个成员,构成开发者感知的全部公开接口:
构造函数:protected constructor(type: BackendType)
| 参数 | 类型 | 说明 |
|---|---|---|
type |
BackendType | 要指定的后端类型 |
该构造器标记为 protected,意味着外部代码无法 new Backend(...),只有子类可以通过 super(type) 调用它。在源码中,两个子类正是这样做的:GoogleAIBackend 调用 super(BackendType.GOOGLE_AI),AgentPlatformBackend 调用 super(BackendType.AGENT_PLATFORM)(见 backend.ts)。
属性:readonly backendType: BackendType
| 修饰符 | 类型 | 说明 |
|---|---|---|
readonly |
BackendType | 指明该后端配置对应的后端类型 |
readonly 表示该属性在构造之后不可再被修改,它的值由构造器传入的 type 决定。由于每个子类在 super() 时已经固定传入了自己的类型常量,因此 backendType 天然成为区分"当前实例属于哪类后端"的稳定标识,供 SDK 内部做类型判断(例如判断是否走 WebSocket 实时通道时,就会检查 backend instanceof AgentPlatformBackend)。
两个官方子类:GoogleAIBackend 与 AgentPlatformBackend
GoogleAIBackend:Gemini Developer API 后端
文档 ai.googleaibackend.md 将其描述为"Gemini Developer API 的配置类",用于在 getAI() 初始化时通过 AIOptions 指定 Gemini Developer API 作为后端。
它的构造器无参数:
export class GoogleAIBackend extends Backend {
constructor() {
super(BackendType.GOOGLE_AI);
}
_getModelPath(project: string, model: string): string {
return `/${DEFAULT_API_VERSION}/projects/${project}/${model}`;
}
_getTemplatePath(project: string, templateId: string): string {
return `/${DEFAULT_API_VERSION}/projects/${project}/templates/${templateId}`;
}
}
从 backend.ts 源码可以看到,它没有额外配置项,直接固定使用 BackendType.GOOGLE_AI,并生成不包含 location 段落的 REST 路径。DEFAULT_API_VERSION 在 constants.ts 中定义为 'v1beta'。
AgentPlatformBackend:Agent Platform(Vertex AI)后端
文档 ai.agentplatformbackend.md 将其描述为"Agent Platform Gemini API(前身为 Vertex AI Gemini API)的配置类"。
与 GoogleAIBackend 的关键区别在于它多了一个 location 配置项:
export class AgentPlatformBackend extends Backend {
readonly location: string = DEFAULT_LOCATION;
constructor(location?: string) {
super(BackendType.AGENT_PLATFORM);
if (location) {
this.location = location;
}
}
_getModelPath(project: string, model: string): string {
return `/${DEFAULT_API_VERSION}/projects/${project}/locations/${this.location}/${model}`;
}
_getTemplatePath(project: string, templateId: string): string {
return `/${DEFAULT_API_VERSION}/projects/${project}/locations/${this.location}/templates/${templateId}`;
}
}
其公开成员如下:
| 成员 | 类型 | 说明 |
|---|---|---|
constructor(location?: string) |
构造器 | 创建 Agent Platform 后端配置对象,location 为区域标识符 |
location |
readonly string |
区域标识符,默认值为 global |
两个关键实现细节(均由 backend.ts 源码确认):
- 默认区域为
global:DEFAULT_LOCATION在 constants.ts 中定义为'global',且类属性直接用它初始化; - 空值回退逻辑:构造器中只有当传入的
location为真值(truthy)时才覆盖默认值。因此传入空字符串、null或undefined时,最终location仍然是'global'——这一行为被测试用例显式覆盖(见下文"测试验证"小节)。
BackendType:后端类型常量体系
BackendType 是一个 enum-like 常量对象,定义在 public-types.ts,官方文档 ai.md 给出的签名为:
BackendType: {
readonly AGENT_PLATFORM: "AGENT_PLATFORM";
readonly GOOGLE_AI: "GOOGLE_AI";
}
| 常量 | 值 | 含义 |
|---|---|---|
AGENT_PLATFORM |
'AGENT_PLATFORM' |
指向 Agent Platform Gemini API(经由 Google Cloud 提供),对应 AgentPlatformBackend |
GOOGLE_AI |
'GOOGLE_AI' |
指向 Gemini Developer API(经由 Google AI / ai.google),对应 GoogleAIBackend |
源码中使用 as const 让字符串值成为字面量类型,并进一步导出类型别名:
export type BackendType = (typeof BackendType)[keyof typeof BackendType];
这样 backendType 属性在类型层面就被收窄为 'AGENT_PLATFORM' | 'GOOGLE_AI' 二者之一,杜绝了非法字符串被误传入的可能。
实际使用:通过 getAI() 与 AIOptions 接入
Backend 是 AIOptions 的组成部分,而 AIOptions 被传给 getAI() 工厂函数。相关类型定义(public-types.ts)为:
export interface AI {
app: FirebaseApp;
backend: Backend;
options?: AIOptions;
}
export interface AIOptions {
backend?: Backend;
useLimitedUseAppCheckTokens?: boolean;
}
在 api.ts 中,getAI() 对 backend 的处理逻辑如下:
export function getAI(app: FirebaseApp = getApp(), options?: AIOptions): AI {
app = getModularInstance(app);
const AIProvider: Provider<'AI'> = _getProvider(app, AI_TYPE);
const backend = options?.backend ?? new GoogleAIBackend(); // 默认后端
const finalOptions: Omit<AIOptions, 'backend'> = {
useLimitedUseAppCheckTokens: options?.useLimitedUseAppCheckTokens ?? false
};
const identifier = encodeInstanceIdentifier(backend);
const aiInstance = AIProvider.getImmediate({ identifier });
aiInstance.options = finalOptions;
return aiInstance;
}
由此可以得到三个明确的官方用法(与 ai.md 文档示例一致):
// 用法一:不传 options,使用默认后端(Gemini Developer API)
const ai = getAI(app);
// 用法二:显式指定 Gemini Developer API 后端
const ai = getAI(app, { backend: new GoogleAIBackend() });
// 用法三:显式指定 Agent Platform Gemini API 后端
const ai = getAI(app, { backend: new AgentPlatformBackend() });
值得注意的默认行为:
- 不传
backend时默认使用GoogleAIBackend(即默认走 Gemini Developer API); - 后端实例被用作实例标识符:
encodeInstanceIdentifier(backend)会根据后端配置生成 identifier,再通过AIProvider.getImmediate({ identifier })获取对应服务实例。这意味着针对同一个 FirebaseApp,使用不同后端(或不同 location)会得到不同的 AI 服务实例,SDK 借此实现了"一个 App 可同时面向不同后端"的能力; - 在 service.ts 中,
AIService的构造器直接接收backend: Backend并持有它,后续所有模型请求都从ai.backend出发构建路径。
源码级原理:Backend 如何决定实际请求 URL
_getModelPath 与 _getTemplatePath 虽然标为 @internal,但它们是理解整个后端抽象的关键。在 requests/request.ts 中,RequestURL 类的 pathname 正是由这两个钩子驱动的:
private get pathname(): string {
if (this.params.templateId) {
return `${this.params.apiSettings.backend._getTemplatePath(
this.params.apiSettings.project,
this.params.templateId
)}:${this.params.task}`;
} else {
return `${this.params.apiSettings.backend._getModelPath(
this.params.apiSettings.project,
(this.params as ModelRequestURLParams).model
)}:${this.params.task}`;
}
}
结合两个子类的实现,可以推导出不同后端最终形成的 REST 路径(DEFAULT_API_VERSION = 'v1beta'):
| 后端 | 模型请求路径(以 project=my-project、model=model-name 为例) |
模板请求路径 |
|---|---|---|
GoogleAIBackend |
/v1beta/projects/my-project/model-name |
/v1beta/projects/my-project/templates/template-id |
AgentPlatformBackend(location=global) |
/v1beta/projects/my-project/locations/global/model-name |
/v1beta/projects/my-project/locations/global/templates/template-id |
AgentPlatformBackend(location=us-central1) |
/v1beta/projects/my-project/locations/us-central1/model-name |
/v1beta/projects/my-project/locations/us-central1/templates/template-id |
路径的 baseUrl 部分默认是 https://${DEFAULT_DOMAIN},其中 DEFAULT_DOMAIN = 'firebasevertexai.googleapis.com'(constants.ts),也可以通过 SingleRequestOptions.baseUrl 覆盖。
此外,后端类型还会影响实时(Live)通道:在 request.ts 的 WebSocketUrl.pathname 中,SDK 用 instanceof AgentPlatformBackend 判断是否走 Agent Platform 的 Bidi 服务,并把自己的 location 拼进 WebSocket 路径:
if (this.apiSettings.backend instanceof AgentPlatformBackend) {
return `ws/google.firebase.vertexai.v1beta.LlmBidiService/BidiGenerateContent/locations/${this.apiSettings.backend.location}`;
}
这说明 location 不仅影响 REST 请求,也影响实时双向通信的 WebSocket 端点,在跨区域部署时务必与后端配置保持一致。
测试验证:行为由用例逐条锁定
仓库中的 backend.test.ts 为上述所有关键行为提供了可验证的测试证据,主要用例包括:
GoogleAIBackend:backendType恒等于BackendType.GOOGLE_AI;_getModelPath('my-project', 'model-name')返回/v1beta/projects/my-project/model-name;_getTemplatePath返回/v1beta/projects/my-project/templates/template-id;AgentPlatformBackend:不传 location 时backendType为AGENT_PLATFORM且location为默认值global;- 传入自定义区域(如
'test-location')时location被正确覆盖; - 传入空字符串
''与null时均回退到默认global,确认了构造器的 truthy 判断逻辑; - Agent Platform 的模型/模板路径中均包含
/locations/${backend.location}/段落。
这些用例与文档描述完全一致,可作为理解 Backend 行为边界的权威参考。
使用建议与注意事项
- 不要直接
new Backend(...):抽象类的 protected 构造器在编译期就会拦截这类调用,应始终通过GoogleAIBackend或AgentPlatformBackend实例化; - 按目标服务选择子类:面向 Gemini Developer API(ai.google)使用
GoogleAIBackend;面向 Google Cloud 上的 Agent Platform / Vertex AI 使用AgentPlatformBackend; - 区域配置只对 Agent Platform 生效:
GoogleAIBackend无 location 概念;AgentPlatformBackend不传 location 时默认global,传空值也会回退到global,需要指定具体区域时传入合法的区域标识符; - 同一个 App 可持有多后端实例:
getAI(app, { backend: ... })中 backend 参与实例标识符的编码,因此可按需为同一 FirebaseApp 创建面向不同后端的独立 AI 实例; - 若需深入排查请求问题,可关注两点:一是最终请求路径由
backend._getModelPath / _getTemplatePath生成(request.ts),二是实时通道端点取决于后端是否为AgentPlatformBackend(request.ts)。