跳轉到主要內容

概述

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