名称: google-gemini-media
描述: 使用 Gemini API(Nano Banana 图像生成、Veo 视频、Gemini TTS 语音与音频理解)提供端到端的多模态媒体工作流和代码模板,涵盖“生成 + 理解”。
许可证: MIT
本技能将 Gemini API 的六项能力整合为可复用的工作流和实现模板:
约定:本技能以官方 Google Gen AI SDK(Node.js/REST)为主线;目前仅提供 Node.js/REST 示例。如果你的项目已封装其他语言或框架,请将本技能的请求结构、模型选择和 I/O 规范映射到你的封装层。
1) 是否需要生成图像?
- 需要从零生成图像或基于图像进行编辑 -> 使用 Nano Banana 图像生成(见第 5 节)
2) 是否需要理解图像?
- 需要识别、描述、问答、比较或信息提取 -> 使用 图像理解(见第 6 节)
3) 是否需要生成视频?
- 需要生成 8 秒视频(可选带原生音频) -> 使用 Veo 3.1 视频生成(见第 7 节)
4) 是否需要理解视频?
- 需要带时间戳的摘要/问答/片段提取 -> 使用 视频理解(见第 8 节)
5) 是否需要朗读文本?
- 需要可控的旁白、播客/有声书风格等 -> 使用 语音生成(TTS)(见第 9 节)
6) 是否需要理解音频?
- 需要音频描述、转录、时间段转录、令牌计数 -> 使用 音频理解(见第 10 节)
npm install @google/genai
curl;如需解析图像 Base64,可安装 jq(可选)。GEMINI_API_KEYx-goog-api-key: $GEMINI_API_KEY内联(嵌入字节/Base64)
- 优点:调用链短,适合小文件。
- 关键限制:总请求大小(文本提示词 + 系统指令 + 嵌入字节)通常有约 20MB 的上限。
Files API(上传后引用)
- 优点:适合大文件、重复使用同一文件或多轮对话。
- 典型流程:
1. files.upload(...)(SDK)或 POST /upload/v1beta/files(REST 可恢复上传)
2. 在 generateContent 中使用 file_data / file_uri
工程建议:实现
ensure_file_uri()函数,当文件超过阈值(例如 10-15MB 警告)或被重复使用时,自动通过 Files API 路由。
inline_data(Base64)形式返回;在 SDK 中使用 part.as_image() 或解码 Base64 并保存为 PNG/JPG。.pcm 或封装为 .wav(通常为 24kHz、16 位、单声道)。重要:模型名称、版本、限制和配额可能随时间变化。使用前请查阅官方文档。最后更新:2026-01-22。
gemini-3-flash-preview 进行图像、视频和音频理解(可根据质量/成本需求选择更强的模型)。veo-3.1-generate-preview(生成 8 秒视频并可原生生成音频)。gemini-2.5-flash-preview-tts(原生 TTS,目前为预览版)。SDK(Node.js)最小模板
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-image",
contents:
"创作一幅在高档餐厅中、带有 Gemini 主题的纳米香蕉菜肴图片",
});
const parts = response.candidates?.[0]?.content?.parts ?? [];
for (const part of parts) {
if (part.text) console.log(part.text);
if (part.inlineData?.data) {
fs.writeFileSync("out.png", Buffer.from(part.inlineData.data, "base64"));
}
}
REST(带 imageConfig)最小模板
curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent" -H "x-goog-api-key: $GEMINI_API_KEY" -H "Content-Type: application/json" -d '{
"contents":[{"parts":[{"text":"创作一幅在高档餐厅中、带有 Gemini 主题的纳米香蕉菜肴图片"}]}],
"generationConfig": {"imageConfig": {"aspectRatio":"16:9"}}
}'
REST 图像解析(Base64 解码)
curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"contents":[{"parts":[{"text":"纳米香蕉的简约工作室产品图"}]}]}' \
| jq -r '.candidates[0].content.parts[] | select(.inline_data) | .inline_data.data' \
| base64 --decode > out.png
# macOS 可使用:base64 -D > out.png
使用场景:给定一张图像,添加/移除/修改元素、改变风格、调色等。
SDK(Node.js)最小模板
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt =
"在桌子上添加一个纳米香蕉,保持光线一致,电影感色调。";
const imageBase64 = fs.readFileSync("input.png").toString("base64");
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-image",
contents: [
{ text: prompt },
{ inlineData: { mimeType: "image/png", data: imageBase64 } },
],
});
const parts = response.candidates?.[0]?.content?.parts ?? [];
for (const part of parts) {
if (part.inlineData?.data) {
fs.writeFileSync("edited.png", Buffer.from(part.inlineData.data, "base64"));
}
}
最佳实践:使用聊天进行连续迭代(例如:先生成,然后“仅编辑特定区域/元素”,接着“生成相同风格的其他变体”)。
要输出混合的“文本 + 图像”结果,请将 response_modalities 设置为 ["TEXT", "IMAGE"]。
你可以在 generationConfig.imageConfig 或 SDK 配置中设置:
- aspectRatio:例如 16:9、1:1。
- imageSize:例如 2K、4K(更高分辨率通常更慢/更昂贵,且模型支持可能不同)。
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const imageBase64 = fs.readFileSync("image.jpg").toString("base64");
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: [
{ inlineData: { mimeType: "image/jpeg", data: imageBase64 } },
{ text: "为这张图像添加描述,并列出任何可见的品牌。" },
],
});
console.log(response.text);
import { GoogleGenAI, createPartFromUri, createUserContent } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const uploaded = await ai.files.upload({ file: "image.jpg" });
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: createUserContent([
createPartFromUri(uploaded.uri, uploaded.mimeType),
"为这张图像添加描述。",
]),
});
console.log(response.text);
在同一 contents 中追加多个图像作为多个 Part 条目;可以混合使用上传引用和内联字节。
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const prompt =
"一个猫宇航员在月球上行走的电影感镜头。包含细微的风声环境音。";
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt,
config: { resolution: "1080p" },
});
while (!operation.done) {
await new Promise((resolve) => setTimeout(resolve, 10_000));
operation = await ai.operations.getVideosOperation({ operation });
}
const video = operation.response?.generatedVideos?.[0]?.video;
if (!video) throw new Error("未返回视频");
await ai.files.download({ file: video, downloadPath: "out.mp4" });
关键点:Veo REST 使用 :predictLongRunning 返回一个操作名称,然后轮询 GET /v1beta/{operation_name};完成后,从响应中的视频 URI 下载。
aspectRatio:"16:9" 或 "9:16"resolution:"720p" | "1080p" | "4k"(更高分辨率通常更慢/更昂贵)轮询回退(带超时/退避)伪代码
const deadline = Date.now() + 300_000; // 5 分钟
let sleepMs = 2000;
while (!operation.done && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, sleepMs));
sleepMs = Math.min(Math.floor(sleepMs * 1.5), 15_000);
operation = await ai.operations.getVideosOperation({ operation });
}
if (!operation.done) throw new Error("视频生成超时");
import { GoogleGenAI, createPartFromUri, createUserContent } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const uploaded = await ai.files.upload({ file: "sample.mp4" });
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: createUserContent([
createPartFromUri(uploaded.uri, uploaded.mimeType),
"总结这个视频。为关键事件提供时间戳。",
]),
});
console.log(response.text);
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-preview-tts",
contents: [{ parts: [{ text: "用欢快的语气说:祝你拥有美好的一天!" }] }],
config: {
responseModalities: ["AUDIO"],
speechConfig: {
voiceConfig: {
prebuiltVoiceConfig: { voiceName: "Kore" },
},
},
},
});
const data =
response.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data ?? "";
if (!data) throw new Error("未返回音频");
fs.writeFileSync("out.pcm", Buffer.from(data, "base64"));
要求:
- 使用 multiSpeakerVoiceConfig
- 每个说话人名称必须与提示词中的对话标签匹配(例如 Joe/Jane)。
voice_name 支持 30 种预置语音(例如 Zephyr、Puck、Charon、Kore 等)。为风格、语速、口音等提供可控的指导,但避免过度约束。
```js
import { GoogleGenAI, createPartFromUri, createUserContent }