> ## 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` 端点，请参阅 [向量嵌入](/cn/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` 对象，适用于需要在多次请求间复用同一段长上下文的场景。与[隐式缓存](/cn/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
