跳转到主要内容

概述

Google 提供 @google/genai(JavaScript / TypeScript)和 google-genai(Python)两套官方 SDK,覆盖 Gemini API 的全部端点。将 baseUrl 指向 AIHubMix 网关并替换为平台 API Key,即可通过原生 SDK 调用 Interactions、Embeddings、Context Caching 等 OpenAI 兼容层未覆盖的能力,无需改动任何业务代码。

快速开始

安装

npm install @google/genai
# 要求 >= 2.0.0;推荐安装 latest
Interactions API 要求 @google/genai >= 2.0.0google-genai >= 2.0.0。低版本 SDK 的请求会被 Google 后端拒绝(legacy Interactions schema no longer supported)。

初始化客户端

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
  apiKey: "sk-***", // 替换为你在 AIHubMix 生成的 API Key
  httpOptions: {
    baseUrl: "https://aihubmix.com/gemini",
  },
});
baseUrl 固定为 https://aihubmix.com/gemini,与 OpenAI 兼容端点 https://aihubmix.com/v1 不同。

Interactions API

Interactions 是 Gemini 新一代推理接口,返回结构化的 Interaction 对象,支持文本生成、原生图像生成(Nano Banana)及多步推理。目前已支持同步模式interactions.create());异步模式(Background Interactions:get / cancel / delete)敬请期待。

文本生成

调用 interactions.create() 发起推理,返回的 Interaction 对象提供 output_text 便捷属性,直接获取模型最后一段文本输出。
const interaction = await ai.interactions.create({
  model: "gemini-3.5-flash",
  input: "用一句话解释量子计算",
});

console.log(interaction.output_text);
console.log(interaction.usage);
// { total_tokens, total_input_tokens, total_output_tokens, ... }

原生图像生成

通过 response_format 配置输出模态为图像。返回的 Interaction 对象提供 output_image 便捷属性,其 data 字段为 Base64 编码的图像数据。
  • 推荐模型 gemini-3.1-flash-image(Nano Banana 2,通用生图模型)。
  • response_modalities 值必须为小写 ['text', 'image'];大写为 generateContent API 的写法,在 Interactions API 中会返回 400
  • 勿传 delivery: 'inline'400 Image delivery mode is not supported),Interactions API 默认即以 inline 方式返回图像数据。
response_format 参数:
字段说明可选值
type输出类型"image"
aspect_ratio宽高比"1:1" "3:4" "4:3" "9:16" "16:9"
image_size输出分辨率"1K" "2K" "4K"
mime_type图像格式"image/png" "image/jpeg"
import fs from "node:fs";

const interaction = await ai.interactions.create({
  model: "gemini-3.1-flash-image",
  input: "A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
  response_modalities: ["text", "image"],
  response_format: { type: "image", aspect_ratio: "1:1", image_size: "1K" },
});

// 方式 1:output_image 便捷属性(取最后一张生成图像)
if (interaction.output_image?.data) {
  fs.writeFileSync("output.png", Buffer.from(interaction.output_image.data, "base64"));
}

// 方式 2:遍历 steps,适用于多步骤混合输出
for (const step of interaction.steps ?? []) {
  for (const block of step.content ?? []) {
    if (block.type === "image" && block.data) {
      fs.writeFileSync("output.png", Buffer.from(block.data, "base64"));
    }
  }
}

流式输出

传入 stream: true 启用 Server-Sent Events(SSE)流式传输。事件按以下顺序到达:
interaction.created → status_update → step.start → step.delta → step.stop → interaction.completed
增量文本通过 event.delta.text 获取,事件类型字段为 event_type
JavaScript
const stream = await ai.interactions.create({
  model: "gemini-3.5-flash",
  input: "写一首关于月亮的俳句",
  stream: true,
});

for await (const event of stream) {
  if (event.event_type === "step.delta" && event.delta?.type === "text") {
    process.stdout.write(event.delta.text);
  }
  if (event.event_type === "interaction.completed") {
    console.log("\nUsage:", JSON.stringify(event.interaction?.usage));
  }
}

Embeddings

通过 embedContent 端点获取文本或多模态内容的向量表示(embedding)。
如需 OpenAI 兼容的 /v1/embeddings 端点,请参阅 向量嵌入

embedContent

const response = await ai.models.embedContent({
  model: "gemini-embedding-2-preview",
  contents: "What is the meaning of life?",
  config: {
    outputDimensionality: 768, // 可选:指定输出维度(128–3072),默认 3072
  },
});

console.log("dimensions:", response.embeddings[0].values.length); // 768

批量获取 Embeddings

embedContentcontents 参数传入 Content 数组,即可一次调用获取多条文本的 embedding:
JavaScript
const response = await ai.models.embedContent({
  model: "gemini-embedding-2-preview",
  contents: [
    { parts: [{ text: "第一段文本" }] },
    { parts: [{ text: "第二段文本" }] },
  ],
});

console.log("count:", response.embeddings.length); // 2
for (const emb of response.embeddings) {
  console.log("dimensions:", emb.values.length);
}

可用模型与参数

模型输入 Token 上限默认输出维度输入模态说明
gemini-embedding-2-preview8,1923,072(推荐 768)文本、图像、视频、音频、PDF最新多模态嵌入模型,支持 outputDimensionality
gemini-embedding-0012,0483,072仅文本上一代文本嵌入模型,支持 taskType
gemini-embedding-001 支持通过 config.taskType 指定嵌入用途,优化特定下游任务的向量质量:
taskType用途
SEMANTIC_SIMILARITY语义相似度计算
RETRIEVAL_DOCUMENT文档索引(被检索侧)
RETRIEVAL_QUERY搜索查询(检索侧)
CLASSIFICATION文本分类
CLUSTERING文本聚类
gemini-embedding-2-preview 不支持 taskType 参数,改为在 prompt 中通过前缀指定任务类型(如 search_query: ...search_document: ...)。

Context Caching(显式缓存)

显式缓存(Explicit Caching)允许开发者手动创建、查询、引用和删除 CachedContent 对象,适用于需要在多次请求间复用同一段长上下文的场景。与隐式缓存不同,显式缓存由应用侧主动管理生命周期。
显式缓存仅适用于 generateContent API。Interactions API 仅支持隐式缓存。
未配置存储定价的模型会被网关拦截缓存创建请求(context caching is not available for model),以防止存储费用漏收。主流模型(gemini-2.5-flash、gemini-2.5-pro 等)均已配置。

创建 CachedContent

通过 caches.create() 创建缓存。ttl(Time-To-Live)控制缓存有效期,到期后自动清除。
const longDocument = "需要反复引用的长文本内容...".repeat(500);

const cache = await ai.caches.create({
  model: "gemini-3.5-flash",
  config: {
    contents: longDocument,
    ttl: "300s",
  },
});

console.log("CachedContent name:", cache.name);
// 格式:cachedContents/xxx

在 generateContent 中引用缓存

cache.name 传入 cachedContent(JS)或 cached_content(Python)参数,即可在推理时命中缓存。命中的 token 数会体现在 usageMetadata.cachedContentTokenCount 中。
const response = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: "请总结上述文档的核心观点",
  config: { cachedContent: cache.name },
});

console.log(response.text);
console.log("cached tokens:", response.usageMetadata?.cachedContentTokenCount);

查询与删除

// 查询 CachedContent 元数据
const info = await ai.caches.get({ name: cache.name });
console.log("model:", info.model, "expireTime:", info.expireTime);

// 删除缓存
await ai.caches.delete({ name: cache.name });

已支持能力矩阵

能力状态说明
generateContent非流式 + 流式
systemInstruction / generationConfigtemperature、maxOutputTokens 等
Structured Output(responseSchemaJSON mode
Function CallingfunctionDeclarations 工具声明
thinkingConfig思维链输出
多模态输入图像 / 音频 / 视频 / PDF via inlineData + Files API
Google Search Grounding搜索增强
countTokensToken 计数
Imagen(generateImagesImagen 3 图像生成
Veo(generateVideos视频生成
TTS语音合成输出
Files API大文件上传与引用
Interactions API新一代推理接口(文本 + Nano Banana 生图)
Embeddings(embedContent原生向量嵌入
Context Caching CRUD显式缓存管理
Live API(WebSocket)暂未支持

常见问题

SDK 版本过低。@google/genai 须 >= 2.0.0,google-genai 须 >= 2.0.0。执行 npm install @google/genai@latestpip install -U google-genai 升级至最新版本。
部分早期模型名称(如 gemini-2.5-flash-image-preview)在 Interactions API 上已下线。请使用当前可用的模型标识符,如 gemini-3.1-flash-image(Nano Banana 2)。generateContent API 不受影响。
Interactions API 的 response_modalities 值必须为小写("text""image")。大写 "TEXT" / "IMAGE"generateContent API 的写法,在 Interactions API 中不被接受。
不可用。SDK 的 vertexai: true 模式要求 GCP OAuth + project / location 参数,与 apiKey 互斥(SDK 抛出 Project/location and API key are mutually exclusive)。通过 AIHubMix 接入时使用 Gemini Developer API 形态即可,后端自动路由。
网关对未配置存储定价的模型会拦截 caches.create() 请求,以防止存储费用漏收。主流模型(gemini-2.5-flash、gemini-2.5-pro 等)均已配置;如遇此错误,请确认该模型是否支持显式缓存。

更新时间:2026-07-07