> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aihubmix.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Gemini 原生 SDK 接入

> 透過 @google/genai SDK 接入 AIHubMix，呼叫 Interactions、Embeddings、Context Caching 等 Gemini API 全部原生能力

## 概述

Google 提供 `@google/genai`（JavaScript / TypeScript）和 `google-genai`（Python）兩套官方 SDK，涵蓋 Gemini API 的全部端點。將 `baseUrl` 指向 AIHubMix 閘道並替換為平台 API Key，即可透過原生 SDK 呼叫 Interactions、Embeddings、Context Caching 等 OpenAI 相容層未覆蓋的能力，無需改動任何業務程式碼。

## 快速開始

### 安裝

<CodeGroup>
  ```bash JavaScript / TypeScript theme={null}
  npm install @google/genai
  # 要求 >= 2.0.0；推薦安裝 latest
  ```

  ```bash Python theme={null}
  pip install -U google-genai
  # 要求 >= 2.0.0
  ```
</CodeGroup>

<Warning>
  Interactions API 要求 `@google/genai` **>= 2.0.0** 或 `google-genai` **>= 2.0.0**。低版本 SDK 的請求會被 Google 後端拒絕（`legacy Interactions schema no longer supported`）。
</Warning>

### 初始化用戶端

<CodeGroup>
  ```js JavaScript theme={null}
  import { GoogleGenAI } from "@google/genai";

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // 替換為你在 AIHubMix 生成的 API Key
    httpOptions: {
      baseUrl: "https://aihubmix.com/gemini",
    },
  });
  ```

  ```python Python theme={null}
  from google import genai

  client = genai.Client(
      api_key="sk-***",  # 替換為你在 AIHubMix 生成的 API Key
      http_options={"base_url": "https://aihubmix.com/gemini"},
  )
  ```
</CodeGroup>

<Tip>
  `baseUrl` 固定為 `https://aihubmix.com/gemini`，與 OpenAI 相容端點 `https://aihubmix.com/v1` 不同。
</Tip>

***

## Interactions API

Interactions 是 Gemini 新一代推理介面，返回結構化的 `Interaction` 物件，支援文字生成、原生圖像生成（Nano Banana）及多步推理。目前已支援**同步模式**（`interactions.create()`）；非同步模式（Background Interactions：`get` / `cancel` / `delete`）敬請期待。

### 文字生成

呼叫 `interactions.create()` 發起推理，返回的 `Interaction` 物件提供 `output_text` 便捷屬性，直接取得模型最後一段文字輸出。

<CodeGroup>
  ```js JavaScript theme={null}
  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, ... }
  ```

  ```python Python theme={null}
  interaction = client.interactions.create(
      model="gemini-3.5-flash",
      input="用一句話解釋量子計算",
  )

  print(interaction.output_text)
  ```
</CodeGroup>

### 原生圖像生成

透過 `response_format` 配置輸出模態為圖像。返回的 `Interaction` 物件提供 `output_image` 便捷屬性，其 `data` 欄位為 Base64 編碼的圖像資料。

<Tip>
  * 推薦模型 `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 方式返回圖像資料。
</Tip>

**`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"`              |

<CodeGroup>
  ```js JavaScript theme={null}
  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"));
      }
    }
  }
  ```

  ```python Python theme={null}
  import base64

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

  # output_image 便捷屬性
  if interaction.output_image:
      with open("output.png", "wb") as f:
          f.write(base64.b64decode(interaction.output_image.data))
  ```
</CodeGroup>

### 串流輸出

傳入 `stream: true` 啟用 Server-Sent Events（SSE）串流傳輸。事件按以下順序到達：

```
interaction.created → status_update → step.start → step.delta → step.stop → interaction.completed
```

增量文字透過 `event.delta.text` 取得，事件類型欄位為 `event_type`。

```js JavaScript theme={null}
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）。

<Tip>
  如需 OpenAI 相容的 `/v1/embeddings` 端點，請參閱 [向量嵌入](/zh-Hant/api/EBD)。
</Tip>

### embedContent

<CodeGroup>
  ```js JavaScript theme={null}
  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
  ```

  ```python Python theme={null}
  from google.genai import types

  result = client.models.embed_content(
      model="gemini-embedding-2-preview",
      contents="What is the meaning of life?",
      config=types.EmbedContentConfig(
          output_dimensionality=768,  # 可選：指定輸出維度（128–3072），預設 3072
      ),
  )

  print(f"dimensions: {len(result.embeddings[0].values)}")  # 768
  ```
</CodeGroup>

### 批次取得 Embeddings

向 `embedContent` 的 `contents` 參數傳入 `Content` 陣列，即可一次呼叫取得多條文字的 embedding：

```js JavaScript theme={null}
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-preview` | 8,192       | 3,072（推薦 768） | 文字、圖像、影片、音訊、PDF | 最新多模態嵌入模型，支援 `outputDimensionality` |
| `gemini-embedding-001`       | 2,048       | 3,072         | 僅文字             | 上一代文字嵌入模型，支援 `taskType`             |

`gemini-embedding-001` 支援透過 `config.taskType` 指定嵌入用途，最佳化特定下游任務的向量品質：

| `taskType`            | 用途         |
| --------------------- | ---------- |
| `SEMANTIC_SIMILARITY` | 語意相似度計算    |
| `RETRIEVAL_DOCUMENT`  | 文件索引（被檢索側） |
| `RETRIEVAL_QUERY`     | 搜尋查詢（檢索側）  |
| `CLASSIFICATION`      | 文字分類       |
| `CLUSTERING`          | 文字聚類       |

<Note>
  `gemini-embedding-2-preview` 不支援 `taskType` 參數，改為在 prompt 中透過前綴指定任務類型（如 `search_query: ...` 或 `search_document: ...`）。
</Note>

***

## Context Caching（顯式快取）

顯式快取（Explicit Caching）允許開發者手動建立、查詢、引用和刪除 `CachedContent` 物件，適用於需要在多次請求間複用同一段長上下文的場景。與[隱式快取](/zh-Hant/api/Gemini-Guides#上下文快取)不同，顯式快取由應用側主動管理生命週期。

<Note>
  顯式快取僅適用於 `generateContent` API。Interactions API 僅支援隱式快取。
</Note>

<Tip>
  未配置儲存定價的模型會被閘道攔截快取建立請求（`context caching is not available for model`），以防止儲存費用漏收。主流模型（gemini-2.5-flash、gemini-2.5-pro 等）均已配置。
</Tip>

### 建立 CachedContent

透過 `caches.create()` 建立快取。`ttl`（Time-To-Live）控制快取有效期，到期後自動清除。

<CodeGroup>
  ```js JavaScript theme={null}
  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
  ```

  ```python Python theme={null}
  long_document = "需要反覆引用的長文字內容..." * 500

  cache = client.caches.create(
      model="gemini-3.5-flash",
      config={
          "contents": long_document,
          "ttl": "300s",
      },
  )

  print(f"CachedContent name: {cache.name}")
  ```
</CodeGroup>

### 在 generateContent 中引用快取

將 `cache.name` 傳入 `cachedContent`（JS）或 `cached_content`（Python）參數，即可在推理時命中快取。命中的 token 數會體現在 `usageMetadata.cachedContentTokenCount` 中。

<CodeGroup>
  ```js JavaScript theme={null}
  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);
  ```

  ```python Python theme={null}
  response = client.models.generate_content(
      model="gemini-3.5-flash",
      contents="請總結上述文件的核心觀點",
      config={"cached_content": cache.name},
  )

  print(response.text)
  print(f"cached tokens: {response.usage_metadata.cached_content_token_count}")
  ```
</CodeGroup>

### 查詢與刪除

<CodeGroup>
  ```js JavaScript theme={null}
  // 查詢 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 });
  ```

  ```python Python theme={null}
  # 查詢 CachedContent 中繼資料
  info = client.caches.get(name=cache.name)
  print(f"model: {info.model}  expire_time: {info.expire_time}")

  # 刪除快取
  client.caches.delete(name=cache.name)
  ```
</CodeGroup>

***

## 已支援能力矩陣

| 能力                                       | 狀態 | 說明                                              |
| ---------------------------------------- | -- | ----------------------------------------------- |
| `generateContent`                        | ✅  | 非串流 + 串流                                        |
| `systemInstruction` / `generationConfig` | ✅  | temperature、maxOutputTokens 等                   |
| Structured Output（`responseSchema`）      | ✅  | JSON mode                                       |
| Function Calling                         | ✅  | `functionDeclarations` 工具宣告                     |
| `thinkingConfig`                         | ✅  | 思維鏈輸出                                           |
| 多模態輸入                                    | ✅  | 圖像 / 音訊 / 影片 / PDF via `inlineData` + Files API |
| Google Search Grounding                  | ✅  | 搜尋增強                                            |
| `countTokens`                            | ✅  | Token 計數                                        |
| Imagen（`generateImages`）                 | ✅  | Imagen 3 圖像生成                                   |
| Veo（`generateVideos`）                    | ✅  | 影片生成                                            |
| TTS                                      | ✅  | 語音合成輸出                                          |
| Files API                                | ✅  | 大檔案上傳與引用                                        |
| Interactions API                         | ✅  | 新一代推理介面（文字 + Nano Banana 生圖）                    |
| Embeddings（`embedContent`）               | ✅  | 原生向量嵌入                                          |
| Context Caching CRUD                     | ✅  | 顯式快取管理                                          |
| Live API（WebSocket）                      | ❌  | 暫未支援                                            |

***

## 常見問題

<AccordionGroup>
  <Accordion title="呼叫 interactions.create() 報 legacy schema 錯誤">
    SDK 版本過低。`@google/genai` 須 >= 2.0.0，`google-genai` 須 >= 2.0.0。執行 `npm install @google/genai@latest` 或 `pip install -U google-genai` 升級至最新版本。
  </Accordion>

  <Accordion title="模型返回 404 Not Found">
    部分早期模型名稱（如 `gemini-2.5-flash-image-preview`）在 Interactions API 上已下線。請使用當前可用的模型識別碼，如 `gemini-3.1-flash-image`（Nano Banana 2）。`generateContent` API 不受影響。
  </Accordion>

  <Accordion title="response_modalities 報 400 Bad Request">
    Interactions API 的 `response_modalities` 值必須為小寫（`"text"`、`"image"`）。大寫 `"TEXT"` / `"IMAGE"` 是 `generateContent` API 的寫法，在 Interactions API 中不被接受。
  </Accordion>

  <Accordion title="vertexai: true 是否可用？">
    不可用。SDK 的 `vertexai: true` 模式要求 GCP OAuth + project / location 參數，與 `apiKey` 互斥（SDK 拋出 `Project/location and API key are mutually exclusive`）。透過 AIHubMix 接入時使用 Gemini Developer API 形態即可，後端自動路由。
  </Accordion>

  <Accordion title="建立快取報 context caching is not available for model">
    閘道對未配置儲存定價的模型會攔截 `caches.create()` 請求，以防止儲存費用漏收。主流模型（gemini-2.5-flash、gemini-2.5-pro 等）均已配置；如遇此錯誤，請確認該模型是否支援顯式快取。
  </Accordion>
</AccordionGroup>

***

更新時間：2026-07-07
