用于 Genkit 的 Google GenAI 插件
这个插件提供了一个连接Google基因AI模型的统一接口,提供通过两个源码的存取 双子座API 编辑 双子企业代理平台它取代了以前的 googleAI 财务报告和审定财务报表 vertexAI 插件 .
用编码代理? 先安装基因组JS技能.
npx skills add genkit-ai/skills --skill developing-genkit-js它教你的代理人 现任Genkit JS APIs 和普通的gitchas. 其他语言的来源、人工安装和技能: 技能/技能。 。 。 .
关于命名的说明: 2026年4月,Google Cloud将Vertex AI重新品牌为: 双子企业代理平台。为了与Google Cloud的基础API基础设施和现有部署保持后向兼容性,这个插件保留了
vertexAI命名空间、导出名称和配置密钥.
正式文件:
安装
npm i --save @genkit-ai/google-genai
配置
此统一插件输出出两个主要初始化器 :
googleAI:允许通过双子座API使用API密钥认证访问模型.vertexAI:允许通过双子企业代理平台(原为Vertex AI)访问模型. 认证可以通过Google Cloud应用程序默认身份(ADC)或更简单的Express ModeAPI密钥进行.
您可以根据您的需要在您的 Genkit 设置中配置一个或两个 .
使用双子座API(googleAI(中文(简体) )
在Google AI Studio提供快速原型和模式访问的理想.
认证 : 需要谷歌 AI API 密钥, 您可以从中获取 谷歌AI工作室。您可以通过设置 GEMINI_API_KEY 或者说 GOOGLE_API_KEY 环境变量,或在插件配置中通过.
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [
googleAI(),
// Or with an explicit API key:
// googleAI({ apiKey: 'your-api-key' }),
],
});
使用双子企业代理平台( U)vertexAI(中文(简体) )
适合应用利用Google Cloud的AI基础设施.
认证方法 :
- 应用程序默认证书( ADC) : 大多数平台的标准方法使用案例,特别是在生产中. 它使用来自环境的证书(例如GCP的服务账户、来自
gcloud auth application-default login(当地) 这种方法需要Google Cloud项目启用计费功能,双子企业代理平台API启用. - 平台快递模式 : 一种简化的方法,使用一个简单的API密钥来尝试许多特性,不需要设置计费或完整的项目配置. 这是快速试验的理想,并且有慷慨的免费配额. 更多了解快递模式。 。 。 .
import { genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [
// Using Application Default Credentials (Recommended for full features)
vertexAI({ location: 'us-central1' }), // Regional endpoint
// vertexAI({ location: 'global' }), // Global endpoint
// OR
// Using Express Mode (Easy to start, some limitations)
// Get an API key from the Agent Platform Studio Express Mode setup.
// vertexAI({ apiKey: process.env.VERTEX_EXPRESS_API_KEY }),
],
});
注意: 当使用 Express 模式时, 您不提供 projectId 财务报告和审定财务报表 location 在插件配置中.
使用双双双双双双 API(googleAI)和双子企业代理平台(vertexAI(中文(简体) )
如果您需要访问两个服务的模型或特性,可以配置两个插件.
import { genkit } from 'genkit';
import { googleAI, vertexAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [
googleAI(),
vertexAI()
],
});
用法实例
通过配置的插件实例访问模型和嵌入器( E)googleAI 或者说 vertexAI) (中文(简体) ).
文本生成( Gemini)
与 googleAI数字 :
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [googleAI()],
});
const response = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: 'Tell me something interesting about Google AI.',
});
console.log(response.text());
与 vertexAI数字 :
import { genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [vertexAI()],
});
const response = await ai.generate({
model: vertexAI.model('gemini-3.1-pro-preview'),
prompt: 'Explain Gemini Enterprise Agent Platform in simple terms.',
});
console.log(response.text());
文本嵌入
与 googleAI数字 :
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [googleAI()],
});
const embeddings = await ai.embed({
embedder: googleAI.embedder('gemini-embedding-2'),
content: 'Embed this text.',
});
与 vertexAI数字 :
import { genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [vertexAI()],
});
const embeddings = await ai.embed({
embedder: vertexAI.embedder('text-embedding-005'),
content: 'Embed this text.',
});
视频理解(代理处理)
与 googleAI,更新型号(如:. gemini-4-argon, (中文(简体) ), gemini-3.8-flash) 能够
探索视频并仅装入所需的部件, 而不是读取帧
固定费率。 这对长相影片更有效. 设定为每个视频
metadata.processing (单位:千美元)'agentic',或 'static',默认值 :
const response = await ai.generate({
model: googleAI.model('gemini-4-argon'),
prompt: [
{
media: { url: 'https://www.youtube.com/watch?v=QO30-W3b_vw' },
metadata: { processing: 'agentic' },
},
{ text: 'What happens in this video? List the main moments with timestamps.' },
],
});
模型的加载步骤回来 custom.processingCall 财务报告和审定财务报表
custom.processingResult 页:1 让他们留在历史中,以采取后续行动
问. response.usage.custom.toolUseTokens 计算已装入的符号.
图像生成
与 googleAI (格米尼图像):
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [googleAI()],
});
const response = await ai.generate({
model: googleAI.model('gemini-nano-banana-2.1'),
prompt: 'A beautiful watercolor painting of a castle in the mountains.',
});
const generatedImage = response.media;
与 vertexAI (格米尼图像):
import { genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [vertexAI()],
});
const response = await ai.generate({
model: vertexAI.model('gemini-3.1-flash-image-preview'),
prompt: 'A beautiful watercolor painting of a castle in the mountains.',
});
const generatedImage = response.media;
视频生成
与 googleAI (格米尼欧姆尼):
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [googleAI()],
});
const response = await ai.generate({
model: googleAI.model('gemini-omni-1.1-flash'),
prompt: 'An origami butterfly flaps its wings and flies out of the french doors into the garden.',
config: {
videoFormat: { aspectRatio: '16:9', resolution: '720p' },
},
});
// An MP4 video (video/mp4), returned inline.
const video = response.media;
- 双子座Omni取代了双子座API上的Veo 3.1预览模型,该模型
2026年10月22日停办. 和Veo不同,这不是一个长期
操作 :
ai.generate()直接返回视频. - 提示中的图像和视频被用作输入(图像到视频,首先) 和最后一个框架、主题参考、编辑或扩展视频.
config.videoFormat套装aspectRatio(单位:千美元)16:9,默认值,或9:16(中文(简体) ) 财务报告和审定财务报表resolution(单位:千美元)360p, (中文(简体) ),720p(默认),1080p或者说4k) (中文(简体) ).delivery: 'uri'返回文件 API URI 而不是内入数据,数据是 建议制作大型视频(一个10 s 4k视频约为50 MB)store: true。用您的 API 密钥下载文件( R)x-goog-api-key头曰. 反应发生后需要几秒钟ACTIVE, (中文(简体) ), 它在48小时后失效.config.videoConfig.task(单位:千美元)text_to_video, (中文(简体) ),image_to_video, (中文(简体) ),reference_to_video, (中文(简体) ),edit, (中文(简体) ),extend)告诉模型 哪种类型的 没有它,模型会从瞬间推断出来.- 在后续转折中编辑生成的视频
store: true通过 上一个响应的消息: 插件继续存储 互动. - 工具没有支持.
与 vertexAI (维奥):
import { genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [vertexAI()],
});
let { operation } = await ai.generate({
model: vertexAI.model('veo-3.1-lite-generate-001'),
prompt: 'An origami butterfly flaps its wings and flies out of the french doors into the garden.',
});
// The generation is asynchronous and returns an operation.
// You must poll the operation until it completes.
while (!operation?.done) {
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
operation = await ai.checkOperation(operation!);
}
// Once complete, the generated video is available in `operation.output`.
音乐生成( Lyria)
与 googleAI数字 :
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [googleAI()],
});
const response = await ai.generate({
model: googleAI.model('lyria-3-clip-preview'),
prompt: 'A cheerful acoustic folk song with guitar and harmonica.',
});
const generatedAudio = response.media;
与 vertexAI数字 :
import { genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [vertexAI()],
});
const response = await ai.generate({
model: vertexAI.model('lyria-3-clip-preview'),
prompt: 'A cheerful acoustic folk song with guitar and harmonica.',
});
const generatedAudio = response.media;
文字对语言
与 googleAI数字 :
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [googleAI()],
});
const response = await ai.generate({
model: googleAI.model('gemini-3.8-flash-tts'),
prompt: [
{
text: 'Have a wonderful day! <laugh>',
// Delivery goes in metadata: the text itself is read verbatim.
metadata: { speechMetadata: { style: 'cheerful and friendly' } },
},
],
config: {
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } },
},
},
});
// A complete WAV file (audio/wav), ready to play or save.
const audio = response.media;
音频格式和流线gemini-3.8-flash-tts, (中文(简体) ), gemini-3.8-flash-lite-tts:
- 无
audioFormat,一个非流化请求返回一个audio/wav文档, 和一个流化请求返回原始 PCM :audio/l1624千赫,单相,16位, 没有标题. - 设定
config.audioFormat.mimeType选择格式 :audio/wav, (中文(简体) ),audio/l16, (中文(简体) ),audio/mulaw或者说audio/alaw。 。 。 .audioFormat.sampleRate也为 已发送, 但模型目前返回 24 kHz . - 流出时,音频块会随着语音生成而来,这样你就可以
在完成前开始演奏. 最后的回答是把他们合为一体
媒体部分。 请求
audio/wav当流到 在结尾获得一个可播放的 WAV 文件( 块本身大多仍然是) 原始PCM).
const { stream, response } = ai.generateStream({
model: googleAI.model('gemini-3.8-flash-lite-tts'),
prompt: 'Have a wonderful day!',
config: {
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } },
},
audioFormat: { mimeType: 'audio/wav' },
},
});
for await (const chunk of stream) {
// chunk.media: the next piece of audio.
}
// One complete WAV file.
const audio = (await response).media;
自主物剂(深度研究和抗重力)
深度研究:
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({ plugins: [googleAI()] });
let { operation } = await ai.generate({
model: googleAI.model('deep-research-preview-04-2026'),
prompt: 'Analyze global semiconductor market trends. Include graphics showing market share changes.',
});
// Deep Research runs asynchronously. Poll until complete.
while (!operation?.done) {
await new Promise((resolve) => setTimeout(resolve, LONG_POLL_INTERVAL_MS));
operation = await ai.checkOperation(operation!);
}
// Once complete, the research report is available in `operation.output`.
反重力:
import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({ plugins: [googleAI()] });
const response = await ai.generate({
model: googleAI.model('antigravity-preview-09-2026'),
prompt: 'Read Hacker News, summarize the top 10 stories.',
// Required: the sandbox the agent works in.
config: { environment: 'remote' },
});
在双子企业代理平台上(vertexAI: 深层研究是
备查 vertexAI.model('deep-research-preview-04-2026') 用于
同样的方式。 它运行在 global 位置(未设置时使用)。 这个
使用服务器默认值 store 除非您设置它( 在请求配置中)
或者说 vertexAI({ store })(三); store: false 照原样发送,代理拒绝
这个.
互动 API 架构( I) response.raw
新的双子体模型通过 googleAI() 插件, 请求通过 Google 的现代路由 互动 API (单位:千美元)/v1beta/interactions而不是遗产 generateContent API (英语).
模式运行
双子座和Gemma模型使用相互作用 API,包括 -latest
化名、剂(深度研究、抗重力)和任何没有列出的型号.
只有这些旧模型仍然使用 generateContent,直到他们退休为止:
gemini-3.5-flashgemini-3.1-flash-litegemini-3.1-pro-previewgemini-3.1-pro-preview-customtoolsgemini-3-flash-previewgemini-2.5-progemini-2.5-flashgemini-2.5-flash-litegemini-3.1-flash-imagegemini-3-pro-imagegemini-2.5-flash-imagegemini-2.5-flash-preview-ttsgemini-2.5-pro-preview-ttsgemini-3.1-flash-tts-previewgemma-4-26b-a4b-itgemma-4-31b-it
模式vertexAI(中文(简体) )
在双子座企业代理平台上,更新了双子座模型(例如:
gemini-4-argon, (中文(简体) ), gemini-3.8-flash双子座 双子座 双子座
以下未列出的模型使用 Interactives API(.../interactions) (中文(简体) ). 这些
模型仍在使用 generateContent数字 :
gemini-3.8-flash-cybergemini-3.5-flashgemini-3.1-flash-litegemini-3.1-pro-preview, (中文(简体) ),gemini-3.1-pro-preview-customtoolsgemini-3-flash-previewgemini-2.5-pro, (中文(简体) ),gemini-2.5-flash, (中文(简体) ),gemini-2.5-flash-lite- 图像模型( e)
gemini-*-image*, (中文(简体) ),gemini-nano-banana-*)和文本对语音 型号(gemini-*-tts*:平台的交互 API 不支持 他们 - 调制模式终点
深度研究也使用"互动"API.
互动 API 可在 global 地点(和 us
财务报告和审定财务报表 eu 多区域有CMEK),并采用Express模式. 如果你没有设置
位置( 无) vertexAI({ location }),没有 GCLOUD_LOCATION,没有
config.location),这些模型使用 global。您设定的位置被用作
,如果该模型无法使用,服务器返回错误。 互动是无国籍的
默认(store: false),如上 googleAI; 设置 config: { store: true }
(或 vertexAI({ store: true }) - 每一份申请 store 赢)
继续之前的谈话
留言。 在使用的模型上
generateContent, (中文(简体) ), store: true 以警告方式被忽略。 与 googleAI, (中文(简体) ),
safetySettings 财务报告和审定财务报表 labels 在这些模型上得到支持.
无国籍谈话中(store: false),服务器侧的早期结果
除了代码执行以外的工具( Google 搜索、 URL 上下文、 Google 地图、 文件)
搜索, MCP 服务器)不随历史一起发送,因为
平台的交互 API 拒绝它们。 模型可能叫这些工具
复; 设置 store: true 以保留服务器上的全部工具历史.
标准基因输出 vs. response.raw
对于常用案例,"源"抽象完全统一: response.text, (中文(简体) ), response.reasoning, (中文(简体) ), response.message,流出(for await (const chunk of stream))),工具同样调用工作,无论使用哪个API后端.
然而,如果你的代码直接检查了通过 response.raw,意识到建筑差异:
generateContent有效载荷 : 回返aGenerateContentResponse与candidates[]元数据和引文位于candidates[0].groundingMetadata。 。 。 .Interactions API有效载荷 : 回返aGeminiInteraction对象为id, (中文(简体) ),status,以及执行时间表数组 :steps[]。 。 。 .- 工具调用 : 中间服务器端工具呼叫(如Google搜索和代码执行)和工具结果总是作为明确步骤(
google_search_call, (中文(简体) ),code_execution_call(见a/c.5/49/70,附件). - 基准引用: 搜索/磁盘定位引号位于
model_output步骤 :import type { GeminiInteraction } from '@genkit-ai/google-genai'; const raw = response.raw as GeminiInteraction; const annotations = raw.steps ?.flatMap((step) => (step.type === 'model_output' ? step.content : [])) .flatMap((c) => (c.type === 'text' ? (c.annotations ?? []) : []));
- 工具调用 : 中间服务器端工具呼叫(如Google搜索和代码执行)和工具结果总是作为明确步骤(
交互路径的关键差异
- 安全设置 : 自定义安全设置不支持在交互路径上 。 这些模型默认不会应用额外的安全过滤器(双子座 API 安全设置); 内置的防止核心伤害的保护总是适用.
BLOCK_NONE设置被忽略了,因为它们无法阻挡任何超出默认的设置. 屏蔽阈值( E)BLOCK_ONLY_HIGH和更加严格)INVALID_ARGUMENT错误, 因此请求的过滤器永远不会静默地被丢弃 . - 采样设置 :
topK没有发送给这些模型( 互动 API 没有)top_k)被丢入了警告.temperature财务报告和审定财务报表topP虽然较新的模型(Gemini 3.6 Flash,3.5 Flash-Lite等)忽略了它们,但仍被发送. - 服务器系统工具调用 : 互动 API 在执行步骤中总是包括中间工具引用,所以
toolConfig.includeServerSideToolInvocations这是不必要的. - 默认无国籍( Explict Store Opt- In) : 上游互动 API 默认将对话存储在 Google 服务器上(
store: true) (中文(简体) ). 为了维护源基特的无国籍、隐私保护行为generateContent,插件明确默认store: false。对于双子座模型,服务器侧存储是一个明确的选择:store: true必须通过请求配置指定( e)config: { store: true })或插件配置(googleAI({ store: true }); 请求store优先,所以config: { store: false }关闭整个插件store: true为这个请求。 当一个交互被存储时,其ID可以在response.message?.metadata?.interactionId在多回合通话中,通过messages: previousResponse.messages与config: { store: true }将自动从消息元数据中取出先前的交互 ID,并状态地继续会话。 如果设置config: { previousInteractionId: "..." }手动,store: true还需要(离家出走)store或通过store: false将扔出一个INVALID_ARGUMENT错误). 在使用的模型上generateContent, (中文(简体) ),store仅控制服务器是否日志您的项目请求( 可以在 AI Studio 的日志和数据集中查看) : 它会像设置时一样发送( 请求配置或googleAI({ store })),否则则适用您的项目日志设置. - 流线 : 文本、媒体和思考摘要流 随即出现。 服务器边工具步骤(Google Search,代码执行,URL上下文,.)在步骤结束时作为完整部分流出,与最终响应中相同. 函数调用为完整
toolRequest当反应结束。 地面工具的使用被计算在内response.usage.custom(例如:.googleSearchCount) (中文(简体) ). - 抗重力需要存储 : 反重力剂不工作
store: false(服务器拒绝),所以与双子座模型不同,它不会默认为store: false· ;store只在设置时发送。 如果你准备好了store: false(在请求中配置或googleAI({ store: false }),它通过,服务器返回出错;使用插件级的Antigravitystore: false设置store: true在请求配置中。 代理商的工作(文件,已安装的软件包) 生活在一个沙盒环境中, 沙盒长期存在, 所以通过messages: previousResponse.messages继续存储的交互,在同一环境中,只发送新消息。 函数工具工作方式相同:将工具结果作为要求它的互动的继续发送. - JSON输出: JSON 无计划输出( Name
output: { format: 'json' },或config: { responseMimeType: 'application/json' })是用一个空的图案发送的,所以在任何形状的JSON中模型答案. 其它responseMimeType值在交互 API 上没有等同值,而是随警告而删除. - 用法 :
response.usage拥有符号总计(inputTokens, (中文(简体) ),outputTokens, (中文(简体) ),thoughtsTokens(中文(简体) ). 按模式计数response.usage.custom(例如:.inputTextTokens, (中文(简体) ),inputImageTokens, (中文(简体) ),outputAudioTokens),和工具使用符号response.usage.custom.toolUseTokens(另见generateContent(原始内容存档于2018-09-26). Models. 字符和媒体部分计数(inputCharacters, (中文(简体) ),inputImages,)从请求和答复中计算,方式与当前相同generateContent模型(Deep Research,一种背景模型,没有.
密钥差异
googleAI:较小型项目的易地设置,与Google AI Studio的原型制作非常出色. 使用 API 键 .vertexAI:企业准备,与Google Cloud IAM和其他核心企业安全功能相融合. 提供更广泛的模式和企业能力、微调和更强有力的治理。 Express Mode提供使用API密钥的低软体切入点.
根据您的工程规模、 基础设施和功能要求选择接口 .
反馈
此套件的来源主要为 精灵 复发. 请提交问题 和拉请求反对的回波.
链接
- 联合国 页:1
- 源代码 : https://github.com/genkit-ai/genkit/tree/main/js/plugins/google-genai 页面存档备份,存于互联网档案馆
- 谷歌AI工作室: https://aistudio.google.com/ 互联网档案馆的存檔,存档日期2013-12-02
- 双子企业代理平台: https://docs.cloud.google.com/gemini-企业-代理平台
- 快捷模式概览 : https://docs.cloud.google.com/gemini-emination-agent-plaft/models/start/express-mode/overview 互联网档案馆的存檔,存档日期2013-12-22
许可证
阿帕奇 - 2.0