ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

Firebase JS SDK 之 LiveModelParams 接口全解析:配置实时多模态生成模型的入参

Firebase JS SDK 之 LiveModelParams 接口全解析:配置实时多模态生成模型的入参
  • 开发工具
  • 后端

【免费下载链接】firebase-js-sdk

Firebase Javascript SDK

项目地址:https://gitcode.com/gh_mirrors/fi/firebase-js-sdk
点击查看免费下载

导读

LiveModelParams是 Firebase AI(firebase/ai)中用于创建实时(Live)生成式模型的参数接口,专门服务于getLiveGenerativeModel()这一入口函数。通过它,开发者可以在一条配置对象中同时指定模型名称、实时生成配置、工具集、工具调用策略与系统指令,从而启动低延迟、双向多模态的 Live 会话。读完本文,你将完整掌握LiveModelParams的全部字段、各字段的底层类型约束,以及如何结合仓库源码理解参数到 WebSocket 会话建立的完整链路。

一、LiveModelParams 是什么:定位与使用入口

1.1 接口定义

在仓库源码 packages/ai/src/types/requests.ts 中,LiveModelParams被定义为:

/** * Params passed to {@link getLiveGenerativeModel}. * @beta */ export interface LiveModelParams { model: string; generationConfig?: LiveGenerationConfig; tools?: Tool[]; toolConfig?: ToolConfig; systemInstruction?: string | Part | Content; }

从源码结构看,它与非实时的ModelParams(同文件第 50-55 行)几乎同构,但有一个关键差异:ModelParams继承自BaseParams(包含safetySettings与generationConfig),而LiveModelParams不继承BaseParams,并且其generationConfig使用的是专门的LiveGenerationConfig类型,而非通用GenerationConfig。这说明实时会话的生成参数与普通请求的生成参数是两套体系,实时场景下没有暴露safetySettings。

1.2 使用入口 getLiveGenerativeModel()

LiveModelParams是 getLiveGenerativeModel() 的唯一入参类型。源码中该函数的行为如下:

export function getLiveGenerativeModel( ai: AI, modelParams: LiveModelParams ): LiveGenerativeModel { if (!modelParams.model) { throw new AIError( AIErrorCode.NO_MODEL, `Must provide a model name for getLiveGenerativeModel. Example: getLiveGenerativeModel(ai, { model: 'my-model-name' })` ); } return new LiveGenerativeModel(ai, modelParams); }

值得注意的两点:

  • model是唯一必填字段,缺失时会抛出AIErrorCode.NO_MODEL错误;
  • 函数本身不做复杂校验,只负责把参数交给LiveGenerativeModel构造函数,真正的参数落盘与使用发生在 packages/ai/src/models/live-generative-model.ts 中:
export class LiveGenerativeModel extends AIModel { generationConfig: LiveGenerationConfig; tools?: Tool[]; toolConfig?: ToolConfig; systemInstruction?: Content; constructor(ai: AI, modelParams: LiveModelParams, ...) { super(ai, modelParams.model); this.generationConfig = modelParams.generationConfig || {}; this.tools = modelParams.tools; this.toolConfig = modelParams.toolConfig; this.systemInstruction = formatSystemInstruction( modelParams.systemInstruction ); } }

构造函数清晰地展示了LiveModelParams五个字段各自的去向:model交给父类AIModel;generationConfig缺省时降级为空对象;tools、toolConfig原样保存;systemInstruction则经过formatSystemInstruction统一格式化为Content。

1.3 关于 Public Preview 状态

接口文档(docs-devsite/ai.livemodelparams.md)与源码均以@beta标注该 API,文档明确提示:"This API is provided as a preview for developers and may change based on feedback... Do not use this API in a production environment."(该 API 仅作为开发者预览提供,可能随反馈调整,请勿在生产环境使用。)同样,getLiveGenerativeModel的文档注释(api.ts)也说明 Live API 仅在现代浏览器窗口与 Node.js ≥ 22 中受支持,且当 Firebase 配置缺失apiKey或projectId时会抛出异常。测试用例 packages/ai/src/api.test.ts 对上述三种抛错场景与正常创建场景均有覆盖验证。

二、model:必填的模型标识

model: string;

model是LiveModelParams中唯一必填属性,表示要连接的 Gemini 实时模型的名称。

在 api.test.ts 中可以验证其具体行为:

it('getLiveGenerativeModel gets a LiveGenerativeModel', () => { const liveGenerativeModel = getLiveGenerativeModel(fakeAI, { model: 'my-model' }); expect(liveGenerativeModel).to.be.an.instanceOf(LiveGenerativeModel); expect(liveGenerativeModel.model).to.equal( 'publishers/google/models/my-model' ); });

从该测试可见,传入'my-model'后,模型属性被规范化为'publishers/google/models/my-model'的完整模型路径形式。进一步的路径拼接逻辑在 live-generative-model.ts 中:

if (this._apiSettings.backend instanceof AgentPlatformBackend) { fullModelPath = `projects/${this._apiSettings.project}/locations/${this._apiSettings.backend.location}/${this.model}`; } else { fullModelPath = `projects/${this._apiSettings.project}/${this.model}`; }

即:使用 Gemini Developer API 后端时,最终建立连接的模型路径为projects/{project}/{model};使用 Agent Platform 后端时,则额外携带locations/{location}段。

三、generationConfig:实时生成参数

generationConfig?: LiveGenerationConfig;

generationConfig用于控制实时内容生成行为,缺省时在构造函数中降级为{}。其类型LiveGenerationConfig定义于 packages/ai/src/types/requests.ts,包含以下可配置项:

字段类型说明
speechConfigSpeechConfig语音合成配置(单说话人或多说话人)
maxOutputTokensnumber响应可生成的最大 token 数,默认不设上限
temperaturenumber采样随机性控制,0 表示始终选取最高概率 token;已废弃(Gemini 3.x 及以上模型会忽略该参数)
topPnumber核采样,从最高概率 token 依次累加至该概率阈值;默认 0.95;已废弃(Gemini 3.x 及以上忽略)
topKnumber从前 K 个最高概率 token 中采样;默认 40;已废弃(Gemini 3.x 及以上忽略)
presencePenaltynumber存在惩罚(正值);已废弃(Gemini 3.x 及以上传入会返回 400)
frequencyPenaltynumber频率惩罚(正值);已废弃(Gemini 3.x 及以上传入会返回 400)
responseModalitiesResponseModality[]响应模态,可选TEXT、IMAGE、AUDIO(见 enums.ts)
inputAudioTranscriptionAudioTranscriptionConfig开启音频输入的转写,结果出现在LiveServerContent消息的inputTranscriptions属性中
outputAudioTranscriptionAudioTranscriptionConfig开启音频输出的转写,结果出现在outputTranscription属性中
contextWindowCompressionContextWindowCompressionConfig上下文窗口压缩配置(Beta)

其中speechConfig是SingleSpeakerSpeechConfig | MultiSpeakerSpeechConfig的联合类型(requests.ts),二者通过never字段互斥:单说话人配置可设置voiceConfig而禁止multiSpeakerVoiceConfig,多说话人配置则相反。

ContextWindowCompressionConfig(requests.ts)支持triggerTokens(触发压缩的 token 阈值)与slidingWindow(滑动窗口机制,其targetTokens表示会话应保留的 token 数)。滑动窗口会丢弃上下文窗口开头的内容,且保证结果始终以user角色的回合起始、系统指令始终保留在开头(requests.ts)。

底层实现细节:在 connect() 方法中,generationConfig的inputAudioTranscription与outputAudioTranscription两个字段会被从配置中拆出,contextWindowCompression也会被单独提取,最终与其余配置一起组装进 WebSocketsetup消息:

const setupMessage: _LiveClientSetup = { setup: { model: fullModelPath, generationConfig, contextWindowCompression, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, inputAudioTranscription, outputAudioTranscription, sessionResumption } };

源码注释明确指出:这两个转写字段在公开 API 中位于 generationConfig 下,但后端期望它们出现在setup消息的顶层——这是理解 Live API 请求结构的关键实现事实。

四、systemInstruction:系统指令

systemInstruction?: string | Part | Content;

systemInstruction用于设定模型的系统级指令(角色、行为约束、任务目标等),支持三种输入形式:

  • string:纯文本指令;
  • Part:单一内容片段(如TextPart);
  • Content:完整的role + parts内容结构。

仓库中Content与Part的定义见 packages/ai/src/types/content.ts:Content由role: Role与parts: Part[]组成;Part是联合类型,涵盖TextPart(文本)、InlineDataPart(内联数据)、FunctionCallPart、FunctionResponsePart、FileDataPart、ExecutableCodePart、CodeExecutionResultPart。

该字段在LiveGenerativeModel构造函数中经由formatSystemInstruction处理(packages/ai/src/requests/request-helpers.ts),处理规则如下:

  • 输入为null/undefined时返回undefined;
  • 输入为字符串时,包装为{ role: 'system', parts: [{ type: 'text', text: input }] };
  • 输入为文本类Part时,深拷贝并补全 part 类型后包装为role: 'system'的 Content;
  • 输入为Content时,深拷贝各 part 并补全类型;若未指定role则强制设为'system',否则保留原有 role。

也就是说,无论开发者传入哪种形式,最终统一归一化为带role的Content结构,再写入 WebSocketsetup消息。

五、tools:可被模型调用的工具集

tools?: Tool[];

tools是模型可调用的工具数组。Tool是联合类型(requests.ts):

export type Tool = | FunctionDeclarationsTool | GoogleMapsTool | GoogleSearchTool | CodeExecutionTool | URLContextTool;

各工具形态如下:

工具结构用途
FunctionDeclarationsTool{ functionDeclarations?: FunctionDeclaration[] }函数声明工具,最多 64 个函数声明;模型可通过FunctionCall请求调用,客户端以FunctionResponse回传结果
GoogleSearchTool{ googleSearch: GoogleSearch }接入 Google 搜索,获取实时网络信息(需遵守相应使用条款)
GoogleMapsTool{ googleMaps: GoogleMaps }接入 Google 地图,获取位置信息(需遵守相应使用条款)
CodeExecutionTool{ codeExecution: {} }启用代码执行能力
URLContextTool{ urlContext: URLContext }通过公开网页 URL 为模型提供额外上下文

其中FunctionDeclaration(requests.ts)包含:name(必须以字母或下划线开头,仅含 a-z、A-Z、0-9、下划线与连字符,最长 64 字符)、description(供模型判断何时调用)、parameters(JSON Schema 格式的参数描述)、functionReference(指向实际函数,设置后模型请求时会被自动调用)。

六、toolConfig:工具调用策略

toolConfig?: ToolConfig;

toolConfig是作用于本次请求全部工具的共享配置(requests.ts):

export interface ToolConfig { functionCallingConfig?: FunctionCallingConfig; retrievalConfig?: RetrievalConfig; }
  • functionCallingConfig(requests.ts)包含mode与allowedFunctionNames。其中mode取值定义于 packages/ai/src/types/enums.ts:
    • AUTO:默认行为,模型自行决定调用函数还是输出自然语言;
    • ANY:强制模型始终预测函数调用;若设置allowed_function_names则限定在这些函数内,否则在提供的function_declarations中任选;
    • NONE:模型不预测任何函数调用,等价于未传函数声明。
  • retrievalConfig(requests.ts)用于数据检索类工具,支持latLng(用户位置)与languageCode(用户语言代码)。

七、典型使用示例

综合上述字段,一个完整的getLiveGenerativeModel调用示例如下:

import { getLiveGenerativeModel } from 'firebase/ai'; const liveModel = getLiveGenerativeModel(ai, { model: 'gemini-2.0-flash-live-001', generationConfig: { responseModalities: ['TEXT', 'AUDIO'], speechConfig: { languageCode: 'zh-CN', voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Aoede' } } }, maxOutputTokens: 2048, inputAudioTranscription: {}, outputAudioTranscription: {} }, systemInstruction: '你是一名友好、简洁的中文语音助手。', tools: [ { functionDeclarations: [ { name: 'get_weather', description: '获取指定城市的天气信息', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] } } ] } ], toolConfig: { functionCallingConfig: { mode: 'AUTO' } } }); const session = await liveModel.connect();

随后即可通过返回的LiveSession进行双向实时交互。需要注意:connect()方法还可接收可选的SessionResumptionConfig(含handle字段)用于恢复之前的会话(requests.ts)。

八、与同类参数接口的对比

在 requests.ts 中,LiveModelParams与以下接口共享相近的字段设计,便于开发者横向迁移:

接口用途与 LiveModelParams 的差异
ModelParams(L50-55)getGenerativeModel()入参继承BaseParams,支持safetySettings;generationConfig为通用GenerationConfig
GenerateContentRequest(L72-77)generateContent()请求体额外包含contents: Content[]
StartChatParams(L388-393)startChat()入参额外包含history?: Content[]

可以看到,LiveModelParams的字段集是这套参数体系中最精简的版本之一——只保留模型、生成配置、工具、工具配置与系统指令五项,配合专门的LiveGenerationConfig,体现了实时场景对低延迟与精简配置的追求。

九、总结

LiveModelParams是 Firebase AI Live API 的配置入口,其五个字段各有明确归属:model决定连接的目标模型路径,generationConfig控制实时生成行为(语音、模态、转写、上下文压缩等),systemInstruction经formatSystemInstruction归一化为系统 Content,tools与toolConfig共同决定模型的工具调用能力与策略。这些参数最终在LiveGenerativeModel.connect()中被组装进 WebSocketsetup消息,建立实时双向会话。由于该 API 目前处于 Public Preview(@beta)阶段,请务必在面向生产环境前关注接口变更。

  • 开发工具
  • 后端

【免费下载链接】firebase-js-sdk

Firebase Javascript SDK

项目地址:https://gitcode.com/gh_mirrors/fi/firebase-js-sdk
点击查看免费下载
上一篇:GLIP项目详解:从语言理解到图像检测的完整流程
下一篇:Bilibili-Evolved资源优先级加载:preload与prefetch

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进